Update parent scope variable in AngularJS

后端 未结 5 1587
不思量自难忘°
不思量自难忘° 2020-11-27 10:45

I have two controllers, one wrapped within another. Now I know the child scope inherits properties from the parent scope but is there a way to update the parent scope variab

5条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 11:36

    There is one more way to do this task and to not use the $scope.$parent variable.

    Just prepare a method for changing the value in parent scope and use it in child one. Like this:

    app.controller('ctrlParent',function($scope) {
      $scope.simpleValue = 'x';
      $scope.changeSimpleValue = function(newVal) {
        $scope.simpleValue = newVal;
      };
    });
    
    app.controller('ctrlChild',function($scope){
        $scope.changeSimpleValue('y');
    });
    

    It also works and give you more control over the value changes.

    You can then also call the method even in HTML like: click me!.

提交回复
热议问题