看ng book1里面第十章的隔離作用域,我對(duì)里面的例子稍加修改以證明隔離作用域和外部作用域是不能互相訪問(wèn)的。代碼如下
<!doctype html>
<html ng-app="myApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0-rc.3/angular.js">
</head>
<body ng-init="outerProperty = 'wow, this is hot'">
Outside myDirective: {{ myProperty }}
Outside Property: {{ outerProperty }}
<div my-directive ng-init="myProperty = 'wow, this is cool'">
Inside myDirective: {{ myProperty }}
Outside Property: {{ outerProperty }}
<div>
<script>
angular.module('myApp', [])
.directive('myDirective', function() {
return {
restrict: 'A',
scope: {}
};
})
</script>
</body>
</html>
運(yùn)行結(jié)果是
Outside myDirective:
Outside Property: wow, this is hot
Inside myDirective: wow, this is cool
Outside Property:
但是當(dāng)我把a(bǔ)ngularJS換成高版本的。例如1.2.13,1.5.0卻發(fā)現(xiàn)這個(gè)結(jié)果不一樣了。
Outside myDirective: wow, this is cool
Outside Property: wow, this is hot
Inside myDirective: wow, this is cool
Outside Property: wow, this is hot
難道新版AngularJS不支持隔離作用域了?于是在AngularJS官網(wǎng)上找隔離作用域,看到新版隔離作用域的用法。
隔離作用域主要是創(chuàng)建可復(fù)用組件,同時(shí)我們還希望外部作用域可以把部分值傳遞給隔離作用域使用。scope配置項(xiàng)是一個(gè)包含綁定作用域?qū)傩缘膶?duì)象。例如scope: { customerInfo: '=info'}將customerInfo同外部屬性info的值進(jìn)行綁定。這樣才能在隔離作用域使用info值指定的屬性值。其他外部的值不能再隔離作用域使用。
例子經(jīng)過(guò)修改,如下
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-example18-production</title>
<script src="../angular/1.2.13/angular.js"></script>
<script>
(function(angular) {
'use strict';
angular.module('docsIsolationExample', [])
.controller('Controller', ['$scope', function($scope) {
$scope.naomi = { name: 'Naomi', address: '1600 Amphitheatre' };
$scope.vojta = { name: 'Vojta', address: '3456 Somewhere Else' };
}])
.controller('anotherController', ['$scope', function($scope) {
$scope.jason = { name: 'Yanfei Qiao', address: 'No. 518 Xinzhuan Rd.' };
}])
.directive('myCustomer', function() {
return {
restrict: 'E',
scope: {
customerInfo: '=info'
},
template: 'Name: {{customerInfo.name}} Address: {{customerInfo.address}} \
<hr> \
Name: {{vojta.name}} Address: {{vojta.address}}'
};
});
})(window.angular);
</script>
</head>
<body ng-app="docsIsolationExample">
<div ng-controller="Controller">
<my-customer info="naomi"></my-customer>
</div>
<div ng-controller="anotherController">
<my-customer info="jason"></my-customer>
</div>
</body>
</html>
輸出結(jié)果如下
Name: Naomi Address: 1600 Amphitheatre
Name: Address:
Name: Yanfei Qiao Address: No. 518 Xinzhuan Rd.
Name: Address: