【问题标题】:how to have unique scope in ng-repeat in angularjs如何在angularjs中的ng-repeat中拥有独特的范围
【发布时间】:2015-05-21 18:30:46
【问题描述】:

我可以为 $scope 设置多个数组吗?

我有一个从 ng-repeat 中的父范围生成的具有子范围的 div 列表。我怎样才能使范围变量单独唯一?

我正在另一个 ng-repeat 中生成一个 ng-repeat 列表。

<div ng-repeat="" ng-init="hide=true" ng-click="hide=!hide">
     <div ng-hide="hide" ng-init="childhide=true" ng-click="childhide=!childhide">
          <div ng-repeat="" ng-init="childhide" ng-hide="childhide">
               <div>{{ variable }}</div>
          </div>
     </div>
</div>

我怎样才能让变量唯一?因为每次当我点击任一 div 时,所有带有 childhide 变量的 div 都会显示。无论如何要让他们单独行动?

谢谢。

【问题讨论】:

  • 我不得不问...你为什么需要它?您是否有需要唯一范围的指令?如果是这样,请使用指令定义的scope 属性来创建自己的范围。

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


【解决方案1】:

要为每个 div 获取一个新的 $scope,首先想到的是创建另一个指令并指定您想要的范围类型。

<div class="container">
    <div ng-repeat="item in items"></div>
</div>

会变成:

<div class="container">
    <inner-directive ng-repeat="item in items"></inner-directive>
</div>

然后在内部指令中:

app.directive('innerDirective', function () {
    return {
        restrict: 'E',
        template: '<div></div>', // this replaces what you had before
        scope: {}
    };
});

这将创建一个隔离范围,它不会从其父级继承属性。

还有其他几个范围选项,但我不记得每个选项的作用。不过在文档中很容易阅读。

【讨论】:

    猜你喜欢
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 2012-11-07
    • 1970-01-01
    • 2014-08-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多