0
我創建了一個簡單的小提琴,以說明scopes (true, false, {})
之間的差異。AngularJS - 範圍差異
但我不明白,爲什麼它,因爲我希望不工作...
1)爲什麼改變在控制器中的「val
」,影響directiveTwo
與「scope:true
」。如果我更改指令中的值,則控制器會停下來影響它。
2)爲什麼directiveThree
具有隔離範圍,但它繼承了控制器的值(因此創建的值爲directiveOne
,傳遞給它),更改控制器中的值會影響directiveThree
。當我更改該指令的值時,它會影響控制器的值。不應該孤立的範圍是孤立的?
Fiddle
HTML:
<div id="myApp" ng-controller="ctrl1">
Controller: <input ng-model="val"/> <b>{{val}}</b> Child: <b>{{childVal}}</b>
<br/>
<div directive-one>
Directive 1: <input ng-model="val"/> Val: <b>{{val}}</b> Child: <b>{{childVal}}</b>
</div>
<div directive-two>
Directive 2: <input ng-model="val"/> Val: <b>{{val}}</b> Child: <b>{{childVal}}</b>
</div>
<div directive-three>
Directive 3: <input ng-model="val"/> Val: <b>{{val}}</b> Child: <b>{{childVal}}</b>
</div>
</div>
的JavaScript:
angular.module("myApp", [])
.controller("ctrl1", function($scope){
$scope.val = "CTRL";
})
.directive("directiveOne", function(){
return {
controller: function($scope){
$scope.childVal = 1;
},
scope:false //or not defined at all
};
})
.directive("directiveTwo", function(){
return {
controller: function($scope){
$scope.childVal = 2;
},
scope:true
};
})
.directive("directiveThree", function(){
return {
controller: function($scope){
$scope.childVal = 3;
},
scope:{}
};
});
angular.bootstrap(document.getElementById('myApp'), ["myApp"]);
也許Angular爲您的指令默認爲'transclude:true'?然後'val'將在指令中可用,並綁定到最外層控制器的模型,從而解釋您所看到的行爲。 –
Thx,我固定了小提琴...我沒有看到指令被橫切。 –
是的,我發現了一個小提琴的修復,並一直在玩一下。如果您將指令DIV的內容移動到指令的模板中,並使用'scope:{}',您將獲得您期望的行爲。所以Angular可能會把DIV的內容放到外部控制器範圍中,因爲當它沒有被定義爲指令的模板時,它不會將它看作指令的一部分。 –