AngularJS嵌套作用域并更改$parent作用域变量

AngularJS nested scopes and altering $parent scope variables

本文关键字:作用域 parent 变量 嵌套 AngularJS      更新时间:2023-09-26

抱歉,如果之前有人问过这个问题,我在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) 

我看不出你给出的简介有任何问题,你需要给我们更多。 我可以提醒您不要尝试在作用域上"共享"嵌套对象。

这个小提琴说明了如果你在孩子身上并且你"覆盖"引用会发生什么。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);
}