1
我在理解如何實例化隔離範圍上的值時遇到了一些麻煩。實例化隔離範圍上的值
該示例中的代碼可以找到here。
在testA
由於我們有控制器設置$scope.name
和$scope.alt
我期望看到AltA和Sam的名稱。相反alt
不可用,並且name
來自父項目。
testB
按預期工作。我們有一個繼承範圍。
testC
也不能按預期方式工作,因爲我們預計該名稱來自name
屬性,而是使用根控制器上的name
。
對我的概念錯誤的地方有幫助嗎?
HTML:
<div ng-controller="RootController">
<h1>name on RootController = {{ name }}</h1>
<div test-a="test-a">
<h1>TestA</h1>
<h2>name is: {{ name }}, expected is Sam</h2>
<h2>alt is: {{ alt }}, expected AltA</h2>
</div>
<div test-b="test-b">
<h1>TestB</h1>
<h2>name is: {{ name }}, expected is Dave</h2>
<h2>scope.alt is: {{ alt }}, expected is AltB</h2>
</div>
<div test-c="test-c" name="Homer">
<h1>TestC</h1>
<h2>name is: {{ name }}, expect Homer</h2>
</div>
</div>
JS:
var app = angular.module('myApp', []);
app.controller('RootController', function($scope) {
//this is set first...
$scope.name = "Bob";
});
// Isolate scope, but why is name not working in controller instantiation
app.directive('testA', function() {
return {
restrict: 'A',
scope: {},
controller: function($scope) {
$scope.name = "Sam"; // Instead it's using value from parent scope
$scope.alt = "AltA"; // Can't be acccessed?
}
};
});
// Inherited scope, works as expected
app.directive('testB', function() {
return {
restrict: 'A',
scope: true,
controller: function($scope) {
$scope.name = 'Dave'; // Overwrites the value on our scope, like we expect
$scope.alt = "AltB"; // Sets this on our scope, like we expect
}
};
});
// Isolate scope, name instantiated from attr
app.directive('testC', function() {
return {
restrict: 'A',
scope: { name: '@' }
};
});
這使得總的感覺,不知道爲什麼我沒有意識到這一點。一直在我的頭上撞了太久。 – Ryan