AngularJS 指令范围未解析("attr name is not defined" 错误)
AngularJS directive scope not resolved ("attr name is not defined" error)
指令代码
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test " + attr.name
}
});
Html
<tr ng-repeat="e in entities">
<td><eicon attr="e"></eicon></td>
</tr>
我遇到了这个错误:ReferenceError: attr is not defined
。怎么了?
由于您声明的是隔离作用域 属性 attr
您应该能够像这样在模板中访问 scope.attr
:
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test {{attr.name}}"
}
});
attr
在范围内可访问,因此您可以在控制器或链接阶段访问 scope.attr
,或在模板中访问 {{attr}}
。一个简单的解决方案是将模板更改为
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test {{attr.name}}",
link: function (scope, element, attrs) {
console.log(scope.attr);
},
controller: function (scope) {
console.log(scope.attr);
}
}
});
指令代码
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test " + attr.name
}
});
Html
<tr ng-repeat="e in entities">
<td><eicon attr="e"></eicon></td>
</tr>
我遇到了这个错误:ReferenceError: attr is not defined
。怎么了?
由于您声明的是隔离作用域 属性 attr
您应该能够像这样在模板中访问 scope.attr
:
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test {{attr.name}}"
}
});
attr
在范围内可访问,因此您可以在控制器或链接阶段访问 scope.attr
,或在模板中访问 {{attr}}
。一个简单的解决方案是将模板更改为
mymodule.directive('eicon', function(){
return {
restrict: 'E',
scope: {
attr: '='
},
template: "test {{attr.name}}",
link: function (scope, element, attrs) {
console.log(scope.attr);
},
controller: function (scope) {
console.log(scope.attr);
}
}
});