【问题标题】:Issues with controller in an ng-repeat communicating data to a different controller, depending on which ng-repeat element was clickedng-repeat 中的控制器问题与不同的控制器通信数据,具体取决于单击的 ng-repeat 元素
【发布时间】:2013-07-05 23:29:24
【问题描述】:

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

我有两个通过服务相互通信的控制器(这是我的 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!";
}

【问题讨论】:

    标签: angularjs angularjs-ng-repeat angularjs-service


    【解决方案1】:

    我可能会这样做,以避免再次重复所有元素。我已经改变了 theService 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!";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 2013-04-05
      相关资源
      最近更新 更多