<!doctype html>
<html ng-app="myApp">
<head>
<script src="http://cdn.bootcss.com/angular.js/1.3.12/angular.min.js"></script>
<script src="http://cdn.bootcss.com/angular-i18n/1.2.15/angular-locale_zh-cn.js"></script></head>
<body>
<div ng-controller="SomeCtrl">
{{ someBareValue }}
<button ng-click="someAction()">Communicate to child</button>
<div ng-controller="ChildCtrl">
{{ someBareValue }}
<button ng-click="childAction()">Communicate to parent</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'+Math.random();
};
})
.controller('ChildCtrl', function($scope) {
$scope.childAction = function() {
$scope.someBareValue = 'hello human, from child';
};
});
</script>
</body>
</html>
这个例子的变量。这个例子中,在已有的 控制器中嵌套了第二个控制器,并且没有设置模型对象的属性。
由于原型继承的关系,修改父级对象中的someBareValue会同时修改子对象中的值,但反之则不行。可以看下这个例子的实际效果,首先点击child button,然后点击parent button。这个例子充分说明了子控制器是复制而非引用someBareValue。
运行一下,即可看出效果。自己整理笔记,搜到的,给你参考。