0

私は次のことをしようとしています:

サービスを介して相互に通信する2つのコントローラーがあります(ここに私のjsFiddleがあります: http://jsfiddle.net/GeorgiAngelov/a9WLr/1/ )。

アイデア:

アイデアは、1 つのコントローラーを変更すると、他のコントローラーのフィールドに反映されるため、ライブアップデート機能が作成されるというものです。ただし、現在の SecondCtrl は 4 つの入力フィールドすべてを同時に更新し、その逆も同様であり、1 つの入力ごとに 4 つすべてを同時に更新します。

私が達成しようとしていること:

私が達成したいことは次のとおりです。コントローラー1の入力フィールドのいずれかをクリックするたびに、コントローラー2の入力ボックスにデータを入力して、コントローラー2が最初にクリックされた入力フィールドを実際に変更できるようにしたい.

HTML

<body ng-app="project"> 
    <div ng-init=" data = [3,4,5,6]">
        <h2>{{name}}</h2>
        <input ng-model="thing.x"/ ng-repeat="singledata in data" ng-controller="FirstCtrl">            
    </div>

    <div ng-controller="SecondCtrl">
        <h2>{{name}}</h2>
        <input ng-model="someThing.x"/>             
    </div>
</body>

JS

var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
    return {
        thing : {
            x : 100
        }
    };
});

function FirstCtrl($scope, theService) {
    $scope.thing = theService.thing;
    $scope.name = "First Controller";
}

function SecondCtrl($scope, theService) {   
    $scope.someThing = theService.thing; 
    $scope.name = "Second Controller!";
}
4

1 に答える 1

3

すべての要素を再び繰り返すことを避けるために、おそらくこのようなことをするでしょう。theServiceAPI は非常に汎用的で、実際の目的が何であるかがよくわからなかったので、APIをいじりました。

実際の例は、http: //jsfiddle.net/BinaryMuse/rpfAV/にあります。

<body ng-app="project"> 
  <div ng-controller="FirstCtrl">
    <h2>{{name}}</h2>
    <input ng-model="theService.things[key]"
      ng-repeat="(key, value) in theService.things" ng-click="edit(key)">
  </div>

  <div ng-controller="SecondCtrl">
    <h2>{{name}}</h2>
    <input ng-model="theService.things[theService.editing]"/>           
  </div>
</body>
var projectModule = angular.module('project',[]);

projectModule.factory('theService', function() {  
  return {
    editing: null,
    things : {
      w : 100,
      x : 200,
      y : 300,
      z : 400
    }
  };
});

function FirstCtrl($scope, theService) {
  $scope.theService = theService;
  $scope.name = "First Controller";
  $scope.edit = function(key) {
    theService.editing = key;
  };
}

function SecondCtrl($scope, theService) {   
  $scope.theService = theService;
  $scope.name = "Second Controller!";
}
于 2013-07-08T17:28:39.880 に答える