angularjs:在 ng-switch 中从控制器更改父范围 [英] angularjs: Change parent scope from controller within a ng-switch

查看:13
本文介绍了angularjs:在 ng-switch 中从控制器更改父范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我可以从子控制器更改模型值,但是当子控制器在 ng-switch 中时,它不起作用,为什么?我创建了一个示例来演示它.

So, I can change a model value from a child controller, but when the child controller is in ng-switch then it doesn't work, why? I created an example to demonstrate it.

避免这种情况的一种方法是在模型名称中使用 .,例如 bunnies.kills.这是错误还是功能?

One way to avoid this is to use the . in the model name, like bunnies.kills. Is this a bug or this is a feature ?

使用 Angular 1.0.6

Using Angular 1.0.6

推荐答案

使用您的代码结构,您需要在子控制器中进行更改:

Using your code structure, in your child controllers you would need to change:

$scope.$parent.kills++;

$scope.$parent.$parent.kills++;

说明:MainCtrl 的作用域是SimpleParentCtrl 的父作用域,但是Step1Ctrl 的祖父作用域和Step2Ctrl.正如其他人指出的那样,ng-switch 创建自己的范围,然后您的 Step1CtrlStep2Ctrl 分别创建了 的子范围>ng-switch.

Explanation: MainCtrl's scope is the parent scope of SimpleParentCtrl, but the grandparent of Step1Ctrl and Step2Ctrl. As some others pointed out, ng-switch creates its own scope, and then your Step1Ctrl and Step2Ctrl each created a child scope of the ng-switch.

注意:每次点击 1 或 2 按钮时,ng-switch 和它当前匹配的子控制器都会获得一个新的作用域.

Note: Each time the 1 or 2 button is clicked, both the ng-switch and it's currently matched child controller get a new scope.

另外:如果您碰巧正在查看 Angular 源代码并想知道 ng-switch 指令如何在没有 scope 的情况下创建自己的范围code> 属性,答案是它通过 scope.$new() 在其链接方法中手动执行此操作.指令 ng-includeng-switchng-repeatng-view 都创建了新的作用域这样,无论是在链接方法中还是在编译方法返回的链接函数中.

Also: In case you happen to be looking in the Angular source and wondering how the ng-switch directive creates its own scope without a scope property, the answer is that it does so manually in its link method via scope.$new(). The directives ng-include, ng-switch, ng-repeat, and ng-view all create new scope this way, either in the link method or the compile method's returned link function.

资源:

https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritancehttp://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m

这篇关于angularjs:在 ng-switch 中从控制器更改父范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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