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

查看:50
本文介绍了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的 outside 外部调用该触发器,因此我需要能够访问局部作用域变量

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.

更新:对于访问子作用域,这可能对您有用:

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天全站免登陆