更新 AngularJS 中的父范围变量

我有两个控制器,一个包裹在另一个里面。现在我知道子范围继承父范围的属性,但是有没有更新父范围变量的方法呢?到目前为止,我还没有找到任何明显的解决方案。

在我的情况下,我在窗体中有一个日历控制器。我希望从父范围(即表单)更新开始和结束日期,以便表单在提交时具有开始和结束日期。

83143 次浏览

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?

When you assign a primitive attribute to a scope, it is always local to the scope (possibly created on the fly), even if a parent scope has an attribute with the same name. This is a design decision, and a good one IMHO.

If you need to change some primitive (ints, booleans, strings) in the parent scope, from the view, you need it to be an attribute of another object in that scope, so the assignment may read:

<a ng-click="viewData.myAttr = 4">Click me!</a>

and it will, in turn:

  1. get the viewData object from whatever scope it is defined in
  2. assign 4 to its myAttr attribute.

This also works (but not sure whether this follows best practice or not)

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


app.controller('ctrlChild',function($scope){
$scope.$parent.simpleValue = 'y';
});

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>.

For accessing variables declared in the parent, we should use $parent in child controller or template file

In controller

$scope.$parent.varaiable_name

In html template

ng-model="$parent.varaiable_name"