作者:LISA_W186 | 来源:互联网 | 2023-01-13 10:30
我一直在使用隔离范围指令一段时间,并且想到了一个问题,看着它的行为:为什么我不能将我在指令继承范围内定义的变量直接绑定到视图?让我举一个关于这个代码笔的例子:http:codepe
我一直在使用隔离范围指令一段时间,并且想到了一个问题,看着它的行为:
为什么我不能将我在指令继承范围内定义的变量直接绑定到视图?
让我举一个关于这个代码笔的例子:
http://codepen.io/anon/pen/VLKjrv
当我在指令控制器中创建一个新的$scope变量,并尝试将其绑定在视图上时,它不起作用.
另一方面,当我将该变量绑定到来自模板指令属性的html时,它确实有效.
看看代码:
angular.module('isolated-test-app', [])
.controller('isolatedTestCtrl', function isolatedTestCtrl($scope){
$scope.test = 'Binded from parent controller';
})
.directive('isolatedDirective', function isolatedDirective(){
var directive = {
scope: {
bindingFromAttr: '=',
},
controller: function directiveController($scope){
$scope.test2 = 'Binded from directive controller!';
},
};
return directive;
})
.directive('isolatedDirectiveNumberTwo', function isolatedDirective2(){
var directive = {
scope: {
bindingFromAttr: '=',
},
template:'\
',
controller: function directiveController($scope){
$scope.test2 = 'Binded from directive controller!';
},
};
return directive;
})
test1
Binded from parent controller
test2
Binded from parent controller
Binded from directive controller!
我期待test1上test2的结果.
为什么会这样?
解决方法:
指令模板与指令元素的内容之间的区别在于适用的范围.
在隔离范围(范围:{})指令中,隔离范围适用于模板,但不适用于内容.内容与指令的父级具有相同的范围.另请注意,如果定义了模板,则内容将被模板替换.要使用除模板之外的内容,需要“transcluding”(transclude:true)(但是,这不属于此答案的范围).
如果您感到困惑,可以随时检查$scope.$id以查看适用的范围:
parent scope: {{$id}} (will be 2)
contents of isolate scope directive: {{$id}} (will also be 2)
contents will be replaced with the template
.directive("isolateScopeWithTemplate", function(){
return {
scope: {},
template: "template: {{$id}} (will NOT be 2)"
}
})
(当然,实际的$id可能不同)
在子范围(范围:true)指令中,应用于内容的范围实际上与应用于模板的范围相同(此处相同 – 模板将替换内容(如果存在,除非您转换).
现在,回答你的问题:
第一个 span>绑定到父作用域中不存在的$scope.test2,因此它是空的.
但是 span>在IsolatedDirectiveNumber模板中,它绑定到该指令的隔离范围,该范围定义了$scope.test2 =’从指令控制器中绑定!’.