所以,我可以从子 Controller 更改模型值,但是当子 Controller 在 ng-switch
中时它不起作用,为什么?我创建了 an example来证明它。
避免这种情况的一种方法是在模型名称中使用 .
,例如 bunnies.kills
。这是错误还是功能?
使用 Angular 1.0.6
最佳答案
使用您的代码结构,您需要在您的子 Controller 中更改:
$scope.$parent.kills++;
到
$scope.$parent.$parent.kills++;
解释:MainCtrl
的范围是 SimpleParentCtrl
的父范围, 但是 Step1Ctrl
的祖 parent 和 Step2Ctrl
.正如其他一些人指出的那样,ng-switch
创建自己的范围,然后是你的 Step1Ctrl
和 Step2Ctrl
每个都创建了 ng-switch
的子范围.
注意:每次单击 1 或 2 按钮时,ng-switch
并且它当前匹配的子 Controller 获得一个新范围。
此外:如果您碰巧正在查看 Angular 源代码并且想知道 ng-switch
是如何产生的指令在没有 scope
的情况下创建自己的范围属性,答案是它通过 scope.$new()
在其链接方法中手动执行此操作.指令 ng-include
, ng-switch
, ng-repeat
, 和 ng-view
都以这种方式创建新范围,无论是在链接方法中还是在编译方法的返回链接函数中。
资源:
https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance http://www.youtube.com/watch?v=ZhfUv0spHCY&feature=youtu.be&t=30m
关于javascript - angularjs:在ng-switch中从 Controller 更改父范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16700813/