javascript - AngularJS directive scope not resolved ("attr name is not defined" error) - Stack Overflow

Directive codemymodule.directive('eicon', function(){return {restrict: 'E',scope: {

Directive code

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>

I've this error: ReferenceError: attr is not defined. What's wrong?

Directive code

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>

I've this error: ReferenceError: attr is not defined. What's wrong?

Share Improve this question asked Feb 8, 2015 at 12:50 brazorfbrazorf 1,9612 gold badges32 silver badges55 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 3

Since you are declaring isolated scope property attr you should be able to access scope.attr in template like this:

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

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

attr is accessible in scope, so you can access scope.attr in your controller or linking phase, or {{attr}} in templates. A simple solution is to change your template to

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745466812a4628950.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信