AngularJS中的2个控制器和1个值

时间:2015-04-21 14:11:06

标签: angularjs

我想拥有一个全局变量,我也在练习AngularJS的工厂和服务功能,并且我很反感这个奇怪的错误。这是错误:(在我的index.html文件中,我像常规一样使用ngRepeat,似乎只有在2个控制器共享全局变量时才会出现此错误)

Error: [ngRepeat:dupes] http://errors.angularjs.org/1.3.15/ngRepeat/dupes?p0=item%20in%20sharedvalue&p1=number%3A0&p2=0
    at Error (native)
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:6:417
    at https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:234:39
    at Object.fn (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:122:291)
    at n.$get.n.$digest (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:123:356)
    at n.$get.n.$apply (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:126:293)
    at HTMLButtonElement.<anonymous> (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:216:126)
    at HTMLButtonElement.c (https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js:32:389)

这是我的代码:

 (function(){
      var app = angular.module("app",[]);
      app.factory('MyFactory', function(){
        return{
          a: 'This is a',
          b: 'This is b',
          c: function(){
            this.a+='a';
            this.b+='b';
          }
        }
      });
      app.service('MyService', function(){
        this.a='This is A';
        this.b='This is B';
        this.c = function(){
          this.a+='A';
          this.b+='B';
        }
      });
      app.controller('SharedFactory', function($scope,MyFactory,SharedValue){
        $scope.a = MyFactory.a;
        $scope.b = MyFactory.b;
        $scope.c = MyFactory.c;
        $scope.sharedvalue = SharedValue;
        var i=0;
        $scope.increase = function(){
          SharedValue.push(i);
          i++;
        };
      });
      app.controller('SharedService', function($scope,MyService,SharedValue){
        $scope.a = MyService.a;
        $scope.b = MyService.b;
        $scope.c = MyService.c;
        $scope.sharedvalue = SharedValue;
        var i=0;
        $scope.increase = function(){
          SharedValue.push(i);
          i++;
        };
      });
      app.value('SharedValue', []);

}());

1 个答案:

答案 0 :(得分:0)

错误很明显:

  

不允许在转发器中重复。使用'track by'表达式指定唯一键。 Repeater:sharedvalue中的项目,Duplicate键:number:0,Duplicate value:0

您在ng-repeat中使用了两次相同的密钥。使用track by,例如:

<div ng-repeat="item in sharedvalue track by $index"></div>