如果之前有人问过这个道歉,我在SO上找不到任何东西,我希望得到一些澄清(或者一个很好的整洁技巧)
给出
<div ng-controller="Parent">
<div ng-controller="Child">
//child manipulation of parent scope object
</div>
</div>
父设置json对象,使其可用于多个子范围 -
$scope.persistentData = getAJSONObject();
子作用域想要进行一些计算并更新它从父作业继承的本地json对象的键 -
doCalculations( $scope.persistentData.keyIWantToAlter )
我是否需要将父作用域明确地分配给子项中的计算函数的结果(如下所示),或者是否有一种方法可以通过仅使用子项的继承范围对象来传播对父作用域的更改?
$parent.$scope.$persistentData.keyIWantToAlter =
doCalculations( $scope.persistentData.keyIWantToAlter)
答案 0 :(得分:2)
我看不出你给你的模糊问题,你需要给我们更多。我可以提醒您尝试在作用域上“共享”嵌套对象。
This fiddle说明了如果您在孩子身边并且“覆盖”该引用会发生什么。 json2
显示这些开始时相同,但我覆盖子范围中的引用,现在变量已分离。
我认为您遇到了类似问题但在提供更多信息之前无法证明这一点。
<div ng-controller="ParentCtrl">
Hello, {{json2}}!
<div ng-controller="ChildCtrl">
Hello, {{json2}}!
</div>
</div>
function ParentCtrl($scope) {
$scope.json2 = {
child:{
name: 'parent'
}
}
}
function ChildCtrl($scope, $timeout) {
$scope.json2 = {
child:{
name: 'child'
}
}
$timeout(function(){
$scope.json2.child.name= 'nick';
},5000);
}