我在理解如何在隔离范围上实例化值时遇到一些麻烦。
可以找到此示例中的代码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: '@' }
};
});
答案 0 :(得分:2)
这是你的傻瓜的工作叉:http://plnkr.co/edit/Oecr5F2tcyioS30g2mYG?p=preview
您需要将模板放入具有隔离范围的指令中,或使用transclude。
这是我对你的第一个指令所做的改变,例如:
app.directive('testA', function() {
return {
restrict: 'A',
template: '<div><h1>TestA</h1><h2>name is: {{ name }}, expected is Sam</h2><h2>alt is: {{ alt }}, expected AltA</h2></div>',
scope: {},
link: function($scope, elem, attrs) {
$scope.name = "Sam"; // Instead it's using value from parent scope
$scope.alt = "AltA"; // Can't be acccessed?
}
};
});