关于angularjs,$scope 交互时最近遇到几个问题
对$scope直接进行赋值
<div ng-controller="SomeCtrl">
{{ someBareValue }}
<button ng-click="someAction()">Communicate </button>
<div ng-controller="ChildCtrl">
{{ someBareValue }}
<button ng-click="childAction()">Communicate </button>
</div>
</div>
<script>
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// anti-pattern, bare value
$scope.someBareValue = 'hello computer';
// set actions on $scope itself, this is okay
$scope.someAction = function() {
$scope.someBareValue = 'hello human, from parent';
};
})
.controller('ChildCtrl', function($scope) {
$scope.childAction = function() {
$scope.someBareValue = 'hello human, from child';
};
});
</script>
效果:子controller只能改变子的,父的可以两个一起变,但是子的改变过后父的就无法再另其改变
对$scope进行对象的赋值引用:
<div ng-controller="SomeCtrl">
{{ someModel.someValue }}
<button ng-click="someAction()">Communicate to child</button>
<div ng-controller="ChildCtrl">
{{ someModel.someValue }}
<button ng-click="childAction()">Communicate to parent</button>
</div>
</div>
<script>
angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
// best practice, always use a model
$scope.someModel = {
someValue: 'hello computer'
}
$scope.someAction = function() {
$scope.someModel.someValue = 'hello human, from parent';
};
})
.controller('ChildCtrl', function($scope) {
$scope.childAction = function() {
$scope.someModel.someValue = 'hello human, from child';
};
});
</script>
效果:这个就是两个都变。。。
总结:在js中,对象,数组,函数是一个引用,类似浅拷贝。但是数值,字符串是值赋值。如果将模型对象的某个属性设置为字符串,它会通过引用进行共享,因此在子的改变也会改变父的。