0

我正在尝试执行以下操作:

我有两个通过服务相互通信的控制器(这是我的 jsFiddle:http: //jsfiddle.net/GeorgiAngelov/a9WLr/1/)。

想法:

这个想法是修改一个控制器将反映在另一个控制器的字段中,从而创建实时更新功能。但是,当前 SecondCtrl 同时更新所有 4 个输入字段,反之亦然,并且每个输入也同时更新所有 4 个。

我要完成的工作:

我想要完成的是:每当我单击控制器一中的任何输入字段时,我希望它填充控制器二的输入框,以便控制器二可以实际修改最初单击的输入字段。

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,因为它非常通用,我不确定它的实际目的是什么。

可以在这里找到一个工作示例: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 回答