angularJS学习之路(七)---子控制器关于是引用机制还是复制机制的问题---原型继承

我们知道在一个应用中可以有  多个控制器,也即是控制器的嵌套  

原型继承 要弄清一点:    修改父级对象中的alue值会同时修改 子对象中的alue值,但是反过来就不行了,

angularJS 中的控制器 嵌套 采用的就是   原型继承的  机制

ps:javascript 对象要么是值复制   要么是 引用复制

首先看第一个例子:

js代码:

var app = angular.module('myApp', []);
app.controller('SomeController', 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';
	};
});
app.controller('ChildController', function($scope) {
	$scope.childAction = function() {
		$scope.someBareValue = 'hello human, from child';
	};
});

HTML代码:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
	</head>

	<body>

		<div ng-app="myApp" ng-controller="SomeController">
			{{ someBareValue }}
			<button ng-click="someAction()">Communicate to child</button>
			<div ng-controller="ChildController">
				{{ someBareValue }}
				<button ng-click="childAction()">Communicate to parent</button>
			</div>
		</div>

		<script type="text/javascript" src="../js/angular.min.js"></script>
		<script type="text/javascript" src="../js/value-copy1.js"></script>
	</body>

</html>

运行结果:

hello computer  Communicate to child

hello computer  Communicate to parent

当你点击第一个按钮 : Communicate to child

显示结果如下所示:

hello human, from parent  Communicate to child

hello human, from parent  Communicate to parent

修改父对象的值,子对象也变了,

然后当你点击第二个对象的时候:Communicate to parent

显示结果如下:

hello human, from parent  Communicate to child

hello human, from child  Communicate to parent

父对象不变,子对象的值发生了变化

如果要想实现同步     就利用  引用进行 共享

下面是代码:

js代码:

var app = angular.module('myApp', []);
app.controller('SomeController', function($scope) {
	// anti-pattern, bare value
	$scope.someModel = {
		someValue: 'hello computer'
	};
	// set actions on $scope itself, this is okay
	$scope.someAction = function() {
		$scope.someModel.someValue = 'hello human, from parent';
	};
});
app.controller('ChildController', function($scope) {
	$scope.childAction = function() {
		$scope.someModel.someValue = 'hello human, from child';
	};
});

下面是HTML代码:

<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
	</head>

	<body>
		<div ng-app="myApp" ng-controller="SomeController">
			{{ someModel.someValue }}
			<button ng-click="someAction()">Communicate to child</button>
			<div ng-controller="ChildController">
				{{ someModel.someValue }}
				<button ng-click="childAction()">Communicate to parent</button>
			</div>
		</div>

		<script type="text/javascript" src="../js/angular.min.js"></script>
		<script type="text/javascript" src="../js/value-copy2.js"></script>
	</body>

</html>

下面是效果:

hello human, from child  Communicate to child

hello human, from child  Communicate to parent

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

扫码关注云+社区

领取腾讯云代金券