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 

hello computer 

当你点击第一个按钮 : 

显示结果如下所示:

hello human, from parent 

hello human, from parent 
修改父对象的值,子对象也变了,


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


显示结果如下:

hello human, from parent 

hello human, from child 

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


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


下面是代码:

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 

hello human, from child 



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值