![](/img/trans.png)
[英]Scope variables not inherited to child controllers from state parent controller
[英]Parent scope variables don't update in the view when child controllers modify them
可以在这里找到关于这个问题的jsFiddle: http : //jsfiddle.net/Hsw9F/1/
JavaScript ( jsFiddle中提供了console.log
调试信息)
var app = angular.module('StackOverflow',[]);
function ParentController($scope) {
$scope.parentCounter = 5;
}
function ChildController($scope) {
$scope.childCounter = $scope.parentCounter;
$scope.increaseCounters = function() {
++$scope.parentCounter;
++$scope.childCounter;
};
}
在上面的示例中,我在父控制器和子控制器中分别有一个计数器,分别命名为parentCounter
和childCounter
。 我还在子控制器中提供了一个名为increaseCounters()
的函数,该函数将两个计数器都增加一个。
这两个计数器都显示在页面上:
<div ng-app="StackOverflow">
<div ng-controller="ParentController">
Parent Counter: {{parentCounter}}<br />
<div ng-controller="ChildController">
Child Counter: {{childCounter}}<br />
<a href="javascript:void(0)"
ng-click="increaseCounters()">Increase Counters</a>
</div><!-- END ChildController -->
</div><!-- END ParentController -->
</div><!-- END StackOverflow app -->
问题是AngularJS似乎不更新页面上的{{parentCounter}}
,而仅在调用增加计数器功能时更新{{childCounter}}
。 有什么我忽略的吗?
++$scope.parentCounter;
创建一个名称为parentCounter
的子范围属性,该属性隐藏/阴影相同名称的父范围属性。
添加console.log($scope);
到您的gainCounters()函数中查看它。
一种解决方法: ++$scope.$parent.parentCounter;
您遇到的问题与JavaScript原型继承的工作方式有关。 我建议阅读AngularJS中范围原型/原型继承的细微差别? -它有一些漂亮的图片,解释了在子范围内创建基元时会发生什么。
因为子控制器获取父计数器值的副本。 如果要增加父控制器的计数器值,则需要在父控制器上执行一个函数:
function ParentController($scope) {
$scope.parentCounter = 5;
$scope.increaseParent = function() {
++$scope.parentCounter;
};
}
function ChildController($scope) {
$scope.childCounter = $scope.parentCounter;
$scope.increaseCounters = function() {
console.log('-------------------------------------');
console.log('parent before: ' + $scope.parentCounter);
console.log('child before: ' + $scope.childCounter);
$scope.increaseParent();
++$scope.childCounter;
console.log('parent after: ' + $scope.parentCounter);
console.log('child after: ' + $scope.childCounter);
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.