简体   繁体   English

从ngRepeat更新$ scope变量

[英]Updating $scope variable from ngRepeat

I have a ngRepeat loop in a view and for every item I have a custom toggle control connected to a $scope variable like this: 我在视图中有一个ngRepeat循环,对于每个项目,我都有一个自定义切换控件连接到$scope变量,如下所示:

<a ng-repeat="item in items" ng-click="isOn = !isOn" ng-class="{on: isOn}">
   Toggle!
</a>

When a link is clicked the isO n variable is toggled as expected, but only for the item clicked . 单击链接时, isO n变量将按预期方式切换,但仅适用于单击的项目 I would expect all items are updated as isOn is defined in controller as $scope.isOn = false 我希望所有项目都将更新,因为isOn在控制器中定义为$scope.isOn = false

When I toggle the variable using controller method all items are updated! 当我使用控制器方法切换变量时, 所有项目都会更新!

<a ng-repeat="item in items" ng-click="toggle()" ng-class="{on: isOn}">
   Toggle!
</a>

--- controller ---

$scope.toggle = function() {
    $scope.isOn = !$scope.isOn;
}

Can you explain this behaviour? 您能解释一下这种行为吗? Is it because ngRepeat is creating a separate scope for every item? 是否因为ngRepeat为每个项目都创建了单独的作用域?

Yes, ngRepeat is creating a separate scope for every item. 是的, ngRepeat正在为每个项目创建一个单独的范围。 See AngularJS ngRepeat 参见AngularJS ngRepeat

The ngRepeat directive instantiates a template once per item from a collection. ngRepeat指令对集合中的每个项目实例化一次模板。 Each template instance gets its own scope... 每个模板实例都有自己的作用域...

Edit: from @doodeec comment 编辑:从@doodeec评论

You could toggle a parent scope instead. 您可以改为切换父作用域。 ng-click="$parent.isOn = !$parent.isOn"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM