AngularJS:指令模板中的数据绑定不适用于ng-repeat

时间:2014-08-07 17:29:38

标签: angularjs angularjs-directive angularjs-scope angularjs-ng-repeat

我创建了这个简单的plunker来演示这个问题:

http://plnkr.co/edit/xzgzsAy9eJCAJR7oWm74?p=preview

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

app.controller('ctrl',function($scope){
  $scope.items = {};
})

app.directive('myDirective',function(){
  return {
    restrict: 'E',
    scope: {
      item: "=item"
    },
    template: "<h2>ng-repeat: </h2>" +
    "<button ng-repeat='i in [1,2,3]' ng-click='item = true'>Set to true</button>" +
    "<h2>no ng-repeat: </h2>" + 
    "<button ng-click='item = false'>Set to false</button>"
  }
})

  <body ng-controller='ctrl'>
    <h1>Item: {{items.someItem}}</h1>
    <my-directive item='items.someItem'></my-directive>
  </body>

当我将模型传递给指令时,双向数据绑定有效,除非从ng-repeat内部访问。 为什么会发生这种情况以及如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

您找到答案here。简而言之,ng-repeat创建一个新范围,一个原始数据类型(布尔值,整数,...),在新范围内按值复制。但是对象({}[])通过指针(而非值)复制,并且在新范围和父范围内相同。

<强>编辑:

我解决了你的案件plnkr

HTML:

<!DOCTYPE html>
<html ng-app='app'>

  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller='ctrl'>
    <h1>Item: {{items.someItem}}</h1>
    <my-directive item='items.someItem'></my-directive>
  </body>

</html>

JavaScript的:

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

app.controller('ctrl', function($scope) {
  $scope.items = {};
})

app.directive('myDirective', function() {
  return {
    restrict: 'E',
    scope: {
      extItem: "=item"
    },
    template: "<h2>ng-repeat: </h2>" +
      "<button ng-repeat='i in [1,2,3]' ng-click='intItem.val = true'>Set to true</button>" +
      "<h2>no ng-repeat: </h2>" +
      "<button ng-click='intItem.val = false'>Set to false</button>",
    link: function(scope, element, attrs) {
      scope.intItem = {
        val: scope.extItem
      };
      scope.$watch('intItem.val', function(){scope.extItem = scope.intItem.val})
    }
  }
})

在此解决方案中,我创建了具有布尔属性intItem的内部对象val,该属性已传入ng-repeat并为$watch添加了intItem.val