angularjs – Angular JS将子作用域变量更改传播到父作用域
我怎么能接受变量的变化,很容易传播他们回到ParentCtrl尽管一个新的var在ChildCtrl实例化?额外点数从最小到没有$和$手表(使其更容易实施)
ParentCtrl > ChildCtrl / ChildCtrl2 / ChildCtrl3 / ChildCtrl4 >查看 我的ChildCtrl的只是不同的,我不能轻易地抽象主布局和ng视图,但他们都依赖于相同的功能在ParentCtrl。 $ scope.searchTerms在ParentCtrl中定义,但ng-model =’searchTerms’的输入框在子控制器的视图中。当这个var改变它不会反映在ParentCtrl只有ChildCtrls。 例: HTML部分 <div ng-app> <div ng-controller="Parent"> parentX = {{x}} <br/> parentY = {{y}}<br/> <div ng-controller="Child"> childX = {{x}}<br/> childY = {{y}}<br/> <a ng-click="modifyBothScopes()">modifyBothScopes</a><br> <br> The changes here need to appear in 'Parent'. <input ng-model='y'> </div> </div> </div> 控制器 function Parent($scope) { $scope.x= 5; $scope.y= 5; } function Child($scope) { $scope.modifyBothScopes= function() { $scope.$parent.x++; }; } 更新 我目前正在尝试共享服务方法:https://gist.github.com/exclsr/3595424 更新 尝试发射/广播系统 解决了 解: 示例:http://jsfiddle.net/JHwxP/23/
这是由于原型继承如何工作。
当在子控制器中请求$ scope.x时,它会检查是否在其作用域上定义了x,如果不是,则在父作用域中查找x。 如果分配给子作用域的x属性,则它仅修改子作用域。 一个简单的方法来处理这个和获得共享行为是使用对象或数组。 function ParentCtrl($scope) { $scope.model = {x: 5,y: 5}; } function ChildCtrl($scope) { $scope.update = function(x,y) { $scope.model.x = x; $scope.model.y = y; }; } 这里,更改将在两个范围中可见,因为$ scope.model将引用父范围和子范围中的同一对象。 约翰·林德奎斯特有一个video on this。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |