Update parent scope variable in angular

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 variable? So far I have not come across any obvious solutions.

In my situation I have a calendar controller within a form. I would like to update the start and end dates from the parent scope (which is the form) so that the form has the start and end dates when submitted.


You need to use an object (not a primitive) in the parent scope and then you will be able to update it directly from the child scope

Parent:

app.controller('ctrlParent',function($scope){
    $scope.parentprimitive = "someprimitive";
    $scope.parentobj = {};
    $scope.parentobj.parentproperty = "someproperty";
});

Child:

app.controller('ctrlChild',function($scope){
    $scope.parentprimitive = "this will NOT modify the parent"; //new child scope variable
    $scope.parentobj.parentproperty = "this WILL modify the parent";
});

Working demo : http://jsfiddle.net/sh0ber/xxNxj/

See What are the nuances of scope prototypal / prototypical inheritance in AngularJS?


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: <a ng-click="changeSimpleValue('y')" href="#">click me!</a> .


这也适用(但不确定这是否遵循最佳实践)

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

app.controller('ctrlChild',function($scope){
    $scope.$parent.simpleValue = 'y';
});
链接地址: http://www.djcxy.com/p/77810.html

上一篇: 在AngularJS中调用一个没有独立范围的指令的控制器函数

下一篇: 更新父范围变量的角度