我使用独立作用域指令已经有一段时间了,观察它的行为时我想到了一个问题:
为什么我不能将我在指令继承范围内定义的变量直接绑定(bind)到 View ?
让我在这个代码笔上展示一个例子: http://codepen.io/anon/pen/VLKjrv
当我在指令 Controller 中创建一个新的 $scope 变量并尝试将其绑定(bind)到 View 时,它不起作用。 另一方面,当我将该变量绑定(bind)到来自模板指令属性的 html 上时,它确实有效。
查看代码:
<body ng-app="isolated-test-app">
<section ng-controller="isolatedTestCtrl">
<article>
<h1>test1</h1>
<div isolated-directive binding-from-attr="test">
<span ng-bind="test"></span>
<span ng-bind="test2"></span>
</div>
<h1>test2</h1>
<div isolated-directive-number-two binding-from-attr="test">
</div>
</article>
</section>
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:'<span ng-bind="bindingFromAttr"></span>\
<span ng-bind="test2"></span>',
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 的结果。
为什么会这样?
最佳答案
指令模板和指令元素的内容在适用范围方面存在差异。
在隔离范围 ( scope: {}
) 指令中,隔离范围适用于模板,但不适用于内容。内容与指令的父级具有相同的范围。另请注意,如果定义了模板,则内容将被模板替换。要使用模板以外的内容,需要“转换”( transclude: true
)(但是,这超出了此答案的范围)。
如果您感到困惑,可以随时查看 $scope.$id
查看适用的范围:
<div>parent scope: {{$id}} (will be 2)</div>
<isolate-scope>
contents of isolate scope directive: {{$id}} (will also be 2)
</isolate-scope>
<isolate-scope-with-template>
contents will be replaced with the template
</isolate-scope-with-template>
.directive("isolateScopeWithTemplate", function(){
return {
scope: {},
template: "template: {{$id}} (will NOT be 2)"
}
})
(当然,实际的 $id
可能不同)
在 child scope ( scope: true
) 指令中,应用于内容的范围实际上与应用于模板的范围相同(此处相同 - 如果模板将替换内容存在,除非你嵌入)。
现在,回答您的问题:
第一个<span ng-bind="test2"></span>
绑定(bind)到一个不存在的 $scope.test2
在父范围内,因此它是空的。
但是 <span ng-bind="test2"></span>
在 isolatedDirectiveNumberTwo
的模板中绑定(bind)到该指令的隔离范围,它定义了 $scope.test2 = 'Binded from directive controller!'
.
关于javascript - 隔离范围 View 绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30362049/