编辑:
在这个 plunker 中有一个功能性的示例:
http://plnkr.co/edit/GFQGP0q3o9RjLAlRANPS?p=preview
外部作用域有 $scope.name = 'Donald'
所有指令都是这样声明的:
<directive-name binding="name">
这是一个多部分问题。我正在尝试更好地理解具有对外部作用域变量的观察或绑定的隔离范围。
使用非隔离范围指令时,一切都正常:
// [WORKS]
.directive('noScopeWithWatch', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) {
scope.$watch(attrs.binding, function(name){
lElement.text('Hello ' + name);
});
}
};
})
// returns Hello Donald
混淆的部分是当我尝试隔离作用域并保持绑定时。因此,我要求对以下一些示例为什么有效而其他示例无效进行澄清。
如果我只是添加了作用域隔离和“正常”的绑定,它会失败:
// 1. [FAILS]
.directive('scopeWithWatch', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) {
scope.$watch(attrs.binding, function(name){
lElement.text('Hello ' + name);
});
},
scope: { // new content
binding: '=' // new content
} // new content
};
})
// returns Hello undefined
然而,在监视器中将绑定变量作为字符串使用可以使其正常工作:
// 2. [WORKS]
.directive('scopeWithWatchString', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) {
scope.$watch('binding', function(b){ // new content
lElement.text('Hello ' + b);
});
},
scope: {
binding: '='
}
};
})
// returns Hello Donald
使用绑定变量作为对象时将会失败:
// 3. [FAILS]
.directive('scopeWithWatchObject', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) {
scope.$watch(binding, function(b){ // new content
lElement.text('Hello ' + b);
});
},
scope: {
binding: '='
}
};
})
// Does not work at all
// Console output - ReferenceError: binding is not defined
尝试在隔离作用域内引用绑定变量也不起作用,但至少不会引发异常:
// 4. [FAILS]
.directive('scopeWithWatchScopeObject', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) {
scope.$watch(scope.binding, function(b){ // new content
lElement.text('Hello ' + b);
});
},
scope: {
binding: '='
}
};
})
// returns Hello undefined
使用模板中的mustaches绑定变量是有效的:
// 5. [WORKS]
.directive('scopeWithTemplate', function(){
return {
restrict: 'E',
template: 'Hello {{binding}}', // new content and linker removed
scope: {
binding: '='
}
};
})
// returns Hello Donald
但是在链接器中尝试将它们用作mustaches是不行的。
// 6. [FAILS]
.directive('scopeWithWatchStringUsingMustashes', function(){
return {
restrict: 'E',
link: function(scope, lElement, attrs) { // new content
scope.$watch('binding', function(){ // new content
lElement.text('Hello {{binding}}'); // new content
}); // new content
}, // new content
scope: {
binding: '='
}
};
})
// returns Hello {{binding}}
这里是Plunker:
http://plnkr.co/edit/GFQGP0q3o9RjLAlRANPS?p=preview (我目前使用的是第78个版本,请fork一下如果你想在你的答案中使用它。)
请有人解释一下为什么有些示例可以工作而其他示例不能。