http://plnkr.co/edit/s64HhVM4b3U5CaMmxcYu?p=preview
var app = angular.module('plunker', []).
run(function($rootScope){
$rootScope.foo='bar';
$rootScope.o={firstName:'john'};
});
app.controller('MainCtrl', function($scope) {
$scope.copyProp=function(){
$scope.o.firstName='Fred';
}
$scope.copyObj=function(){
$scope.o={firstName:'Jack'};
}
$scope.copyVar=function(){
$scope.foo='test';
}
});
Can anyone explain what's happening here, if I copy an objects property it stays in sync with root. If I copy the object it goes 'out of sync' the variable doesn't work at all. Am I correct to assume everything outside the redbox is the rootscope?
1 个答案:
答案 0 :(得分:0)
$rootScope.o={firstName:'john'};
...
$scope.o.firstName='Fred';
Until now, $scope has no property o. So when you access $scope.o JavaScript looks for o in the parent scope up to the root scope until it finds o. At this point $scope.o is $rootScope.o. They are not synced, they are the same.
$scope.o={firstName:'Jack'};
Now $scope gets its own property o, that is independent from $rootScope.o. Consequently $scope.o.firstName='Fred'; does not change $rootScope.o. They have nothing to do with each other.