嵌套 ng-repeat $parent.$index 和 $index [英] nested ng-repeat $parent.$index and $index

查看:23
本文介绍了嵌套 ng-repeat $parent.$index 和 $index的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个奇怪的错误,不幸的是,我无法使用 jsfiddle 进行复制.除了以下片段之外,我已经注释掉了我的整个代码(除了库等).有什么明显的我不明白的地方吗?有什么想法吗?

这有效并打印:(0,0) (0,1) (1,0) (1,1)

<div ng-repeat="j in list2"><div>({{$parent.$index}} {{$index}})

然而,这段代码打印:(0,0) (1,1) (0,0) (1,1)

<div ng-repeat="j in list2"><div ng-if="1">({{$parent.$index}} {{$index}})

我的控制器是:

$scope.list = [1, 2];$scope.list2 = [1, 2];

解决方案

DEMO FIDDLE

那是因为指令 ng-if 为自己创建了一个新的作用域,当你引用 $parent 时,它会访问直接的 $parent> 的作用域,即内部重复表达式的作用域.

所以如果你想实现你想要的东西,比如前者,你可以使用这个:

<div ng-repeat="j in list2"><div ng-if="1">({{$parent.$parent.$index}} {{$parent.$index}})

如果您有多个内部指令,您可以使用 ng-init$index 存储在变量中以供子作用域中的引用.

<div ng-repeat="j in list2" ng-init="innerIndex=$index"><div ng-if="1">({{outerIndex}} {{innerIndex}})

我强烈建议您阅读这篇关于理解角度中的作用域

I have a strange bug that, unfortunately, I cannot replicate with jsfiddle. I've commented out my entire code (Except libraries,etc) except for the following snippets. Is there something obvious that I don't understand? Any ideas?

This works and prints: (0,0) (0,1) (1,0) (1,1)

<div ng-repeat="i in list">
    <div ng-repeat="j in list2">
        <div>
            ({{$parent.$index}} {{$index}})
        </div>
    </div>
</div>

However, this piece of code prints: (0,0) (1,1) (0,0) (1,1)

<div ng-repeat="i in list">
    <div ng-repeat="j in list2">
        <div ng-if="1">
            ({{$parent.$index}} {{$index}})
        </div>
    </div>
</div>

My controller is:

$scope.list  = [1, 2];
$scope.list2 = [1, 2];

解决方案

DEMO FIDDLE

That's because the directive ng-if creates a new scope for itself, when you refer to $parent, it access the immediate $parent's scope, i.e., the inner repeat expression's scope.

So if you want to achieve something you wanted like in the former, you may use this:

<div ng-repeat="i in list">
    <div ng-repeat="j in list2">
        <div ng-if="1">
            ({{$parent.$parent.$index}} {{$parent.$index}})
        </div>
    </div>
</div>

if you have more than one inner directives, you can use ng-init for storing $index in a variable for references in child scopes.

<div ng-repeat="i in list" ng-init="outerIndex=$index">
    <div ng-repeat="j in list2" ng-init="innerIndex=$index">
        <div ng-if="1">
            ({{outerIndex}} {{innerIndex}})
        </div>
    </div>
</div>

I strongly suggest you to go through this article on understanding scopes in angular

这篇关于嵌套 ng-repeat $parent.$index 和 $index的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆