AngularJS指令作用域未解析(“属性名称未定义”错误)

AngularJS directive scope not resolved ("attr name is not defined" error)

本文关键字:未定义 错误 属性 作用域 指令 AngularJS      更新时间:2023-09-26

指令代码

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}}"
    }
});

演示:http://plnkr.co/edit/YZ0aPqhkMlIIwmrkKK2v?p=preview

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);
        }
    }
});