【问题标题】:AngularJS : Data binding in directive template doesn't work with ng-repeatAngularJS:指令模板中的数据绑定不适用于 ng-repeat
【发布时间】:2014-08-07 17:29:37
【问题描述】:

我创建了这个简单的 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 内部访问的。 为什么会发生这种情况以及如何解决这个问题?

【问题讨论】:

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


    【解决方案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})
        }
      }
    })
    

    在这个解决方案中,我创建了带有布尔属性 val 的内部对象 intItem,它传递到 ng-repeat 并为 intItem.val 添加了 $watch

    【讨论】:

    • 感谢您的回复。我想通了,但是有没有办法直接传递对象?目前,对于我的指令,我并不总是想设置 someItem。我希望能够将它传递给指令。所以,我现在的解决方案是使用这样的属性: ,然后在指令 ng-click="items[item] = true" 中,但我认为这是只是错了。
    • @tuks 我改了答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-28
    相关资源
    最近更新 更多