AngularJS指令范围未解析(" attr name未定义"错误)

时间:2015-02-08 12:50:34

标签: javascript angularjs angularjs-directive

指令代码

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。怎么了?

2 个答案:

答案 0 :(得分:3)

由于您要声明隔离的范围属性attr,您应该能够在模板中访问scope.attr,如下所示:

mymodule.directive('eicon', function(){
    return {
        restrict: 'E',
        scope: {
            attr: '='
        },
        template: "test {{attr.name}}"
    }
});

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

答案 1 :(得分:2)

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