同步子作用域var和父作用域var [英] Sync child scope var with parent var
问题描述
我有一个关于角度决定如何创建新的子范围变量的问题.
I have a question about how angular decides to create new child scope variable.
http://plnkr.co/edit/Dlsh6WJA1hrCpBgm5IrI?p=preview
JS
angular.module('myapp', [])
.controller('HomeCtrl', function($scope) {
$scope.aaa = 10;
$scope.clickMe2 = function() {
$scope.aaa++;
}
})
.controller('TestCtrl', function($scope) {
$scope.clickMe1 = function() {
$scope.aaa = $scope.$parent.aaa || 9;
$scope.aaa++;
}
})
HTML
<div ng-controller="HomeCtrl">
<p>{{ aaa }}</p>
<a ng-click="clickMe2()" href="">Click Parent</a>
<div ng-controller="TestCtrl" style="padding-left:20px;">
<p>{{ aaa }}</p>
<a ng-click="clickMe1()" href="">Click Child</a>
</div>
</div>
这就是我所做的:
-
单击父级"以查看两个数字都增加了
Click Parent to see both numbers increased
然后单击子级"以查看第二个数字增加的次数一次
Then Click Child to see the second number increased ONCE
返回上一步单击父级"以仅看到第一个增加的数字
Go back Click Parent to see only the first number increased
最后一次单击子级"以查看其从父级号开始,然后再次增加一次,
Finally Click Child again to see it started from the parent number and again, increased ONCE
我的问题:不使用服务,是否有办法始终确保子范围的变量与父范围的变量相同?看来我的作业$scope.aaa = $scope.$parent.aaa
并非一直有效.
My question: Without using services, is there a way to always ensure the child scope's variable IS the same as the parent scope's variable? Look like my assignment $scope.aaa = $scope.$parent.aaa
doesn't work all the times.
推荐答案
我有办法始终确保子范围的变量与父范围的变量相同:使用Object,以便它们使用相同的引用.
I have a way to always ensure the child scope's variable IS the same as the parent scope's variable: use Object so they use the same reference.
我进行了一些更改,您可以使用:
I have made some changes, you can use:
JS
angular.module('myapp', [])
.controller('HomeCtrl', function($scope) {
$scope.aaa = {a:10}; //change here.
$scope.clickMe2 = function() {
$scope.aaa.a++; //here.
}
})
.controller('TestCtrl', function($scope) {
$scope.clickMe1 = function() {
$scope.aaa.a = $scope.$parent.aaa.a || 9; //here.
$scope.aaa.a++; //here.
}
})
HTML
<div ng-controller="HomeCtrl">
<p>{{ aaa.a }}</p> //here.
<a ng-click="clickMe2()" href="">Click Parent</a>
<div ng-controller="TestCtrl" style="padding-left:20px;">
<p>{{ aaa.a }}</p> //and here.
<a ng-click="clickMe1()" href="">Click Child</a>
</div>
</div>
这篇关于同步子作用域var和父作用域var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!