我在我的一个指令中使用了Scope Isolation。但是,这似乎不起作用:
<div ng-controller="MyCtrl">
Hello, {{name}}!
<dir info='spec'>
{{ data }}
</dir>
</div>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
$scope.name = 'Superhero';
$scope.spec = 'Super';
}
myApp.directive('dir', function(){
return {
restrict: 'AE',
scope:{
data: '=info'
}
}
});
答案 0 :(得分:2)
这是一个小提琴:http://jsfiddle.net/WA5t5/
自this commit( 1.2 )以来在应用程序模板或其他模板中定义的子元素 指令模板没有得到隔离范围。
您可以这样做:
myApp.directive('dir', function(){
return {
restrict: 'AE',
scope:{
data: '=info'
},
template: "{{ data }}"
}
});
如果您想更改此行为,请查看我的其他答案:Why I can't access the right scope?
答案 1 :(得分:0)
尝试:
myApp.directive('dir', function(){
return {
restrict: 'AE',
scope:{
data: '=info'
},
template:"<div>{{data}}</div>"
}
});
使用transclusion自行绑定范围的另一种解决方案:
myApp.directive('dir', function(){
return {
restrict: 'AE',
scope:{
data: '=info'
},
transclude:true,
compile: function (element, attr, linker) {
return function (scope, element, attr) {
linker(scope, function(clone){
element.append(clone); // add to DOM
});
};
}
}
});
您仍然可以使用与之前相同的HTML:
<div ng-controller="MyCtrl">
Hello, {{name}}!
<dir info='spec'>
{{data}}
</dir>
</div>
答案 2 :(得分:0)
您应该在指令中定义一个模板,您可以在其中显示数据范围变量。 html代码不知道数据范围变量是什么,它只在指令的模板中知道。见demo
myApp.directive('dir', function () {
return {
restrict: 'AE',
scope: {
data: '=info'
},
link: function (scope, element, attrs) {
console.log(scope.data);
},
template: 'Hello {{data}}'
}
});