【问题标题】:How do you access an ng-repeat item in a directive's scope?您如何访问指令范围内的 ng-repeat 项?
【发布时间】:2013-01-17 10:22:02
【问题描述】:

你如何为这样的东西设置范围值:

<div ng-controller="MyCtrl">
      <my-element ng-repeat="p in people" person='p'></my-element>
</div>
var myApp = angular.module('myApp',[]);

myApp.directive('myElement', function(){
    return {
        restrict: 'E',
        template: '<div>{{ name }}</div> <div>{{ age }}</div>'
    }
});

function MyCtrl($scope) {
    $scope.people = [{ name: 'Mike', age: 20 },{name: 'Peter', age: 22 }];
}

【问题讨论】:

    标签: angularjs angularjs-directive


    【解决方案1】:

    您不需要在指令中创建隔离范围。 ng repeat 会自动为您执行此操作。 所以只需删除:

    在指令中:

    scope: {
       person: '='
    },
    

    并在 ng 中重复 html 标记:

    person='p'
    

    在您的指令中,您将能够访问类似

    的内容
    $scope.p.personAttribute
    

    就像这里的解释中提到的: angularjs-pass-instance-of-each-ng-repeat-in-html-to-directive

    【讨论】:

      【解决方案2】:

      我喜欢在定义指令范围时使用“@”。这使得指令隔离范围能够访问 p,例如在链接中:

      return {
         scope: '@',
         link: function(scope) {
             console.log(scope.p); //It can now be accessed because of '@'
         }
      }
      

      【讨论】:

      • 在您的示例中,它也可以在没有“@”的情况下访问
      【解决方案3】:

      如果“设置范围值”是指让模板工作,那么

      template: '<div>{{ p.name }}</div> <div>{{ p.age }}</div>'
      

      由于 ng-repeat 的每次迭代都会创建一个新的子作用域,因此在该作用域上定义了 p。由于您的指令没有创建隔离范围,因此您不需要属性person,因此适用于上述内容:

      <my-element ng-repeat="p in people"></my-element>
      

      如果您想要一个隔离范围,请使用

      <my-element ng-repeat="p in people" person='p'></my-element>
      

      return {
         restrict: 'E',
         scope: {
             person: '='
         },
         template: '<div>{{ person.name }}</div> <div>{{ person.age }}</div>'
      }
      

      【讨论】:

      • 此表单ng-repeat="p in people" person='p' 是否仍然有效。我没有在文档中看到它并给我错误。谢谢
      • 第一种形式比较脆弱,因为它依赖于循环变量名,由指令的用户选择...第二种形式很好用,谢谢分享。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-07-01
      • 1970-01-01
      • 2014-10-25
      • 1970-01-01
      • 1970-01-01
      • 2016-11-28
      • 2021-09-28
      相关资源
      最近更新 更多