【问题标题】:AngularJS directive scope not resolved ("attr name is not defined" error)AngularJS 指令范围未解析(“未定义属性名称”错误)
【发布时间】:2015-02-08 12:50:34
【问题描述】:

指令代码

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

【问题讨论】:

    标签: javascript angularjs angularjs-directive


    【解决方案1】:

    由于您声明了隔离范围属性attr,您应该能够像这样在模板中访问scope.attr

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

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

    【讨论】:

    • 如果我需要访问代码怎么办?该模板将取决于该值
    • “访问代码”是什么意思?您是在谈论可以使用scope.attr 对象操作的链接功能吗?
    • @dfsq 你可以查看我对样本的回答
    【解决方案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);
            }
        }
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-11
      相关资源
      最近更新 更多