AngularJS:在 ng-repeat 生成的范围内设置变量 [英] AngularJS: Setting a variable in a ng-repeat generated scope

查看:22
本文介绍了AngularJS:在 ng-repeat 生成的范围内设置变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何访问由 ng-repeat 生成的一组范围?

How do I access the set of scopes generated by an ng-repeat?

我想这的核心是我不太明白 a) 传递给 ng-repeat 指令的对象集合和 b) 它生成的范围集合之间的关系是如何工作的.我可以尝试使用 (a),ng-repeat 作用域会监视并拾取它,但是如何在作用域本身上设置变量 (b)?

I suppose at the heart of this is the fact that I don't understand quite how the relationship works between a) the collection of objects that I pass into the ng-repeat directive and b) the collection of scopes that it generates. I can play around with (a), which the ng-repeat scope watches and picks up, but how do I set variables on the scope itself (b)?

我的用例是我有一组使用 ng-repeat 重复的元素,每个元素都有一个使用 ng-show/ng-hide 切换的编辑视图;每个元素的状态保存在局部作用域的变量中.我希望能够在特定元素上触发 ng-show,但我希望从 外部 ng-repeat 调用触发器,因此我需要能够访问局部范围变量.

My use case is that I have a set of elements repeating using ng-repeat, each of which has an edit view that gets toggled using ng-show/ng-hide; the state for each element is held in a variable in the local scope. I want to be able to trigger an ng-show on a particular element, but I want the trigger to be called from outside the ng-repeat, so I need to be able to access the local scope variable.

谁能指出我正确的方向(或者告诉我我是否在吠错树)?

Can anyone point me in the right direction (or tell me if I'm barking up the wrong tree)?

谢谢

更新:下面的链接非常有用,谢谢.最后,我为每个重复元素创建了一个指令,并使用指令的链接函数将其作用域添加到根作用域的集合中.

Update: Link below was very helpful thankful. In the end I created a directive for each of the repeating elements, and used the directive's link function to add its scope to a collection on the root scope.

推荐答案

在范围层次结构中工作时,我发现使用 $emit 和 $broadcast 调度事件非常有用.$emit 向上调度事件,以便您的子作用域可以通知特定事件的父作用域.$broadcast 正好相反.

When working within a hierarchy of scopes I find very useful to dispatch events with $emit and $broadcast. $emit dispatches an event upwards so your child scopes can notify parent scopes of a particular event. $broadcast is the other way round.

或者,由于子作用域可以访问父作用域属性,您可以通过对父作用域中的特定属性使用 $watch 来触发更改.

Alternatively, as child scopes have access to parent scope properties you could trigger changes by using $watch on a particular property in the parent scope.

更新:至于访问子作用域,这可能对您有用:根据父作用域获取Angularjs中的所有子作用域

UPDATE: As for accessing the child scopes, this may turn useful for you : Get to get all child scopes in Angularjs given the parent scope

这篇关于AngularJS:在 ng-repeat 生成的范围内设置变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆