AngularJS: Objects inside nested directives getting undefined?

别说谁变了你拦得住时间么 提交于 2019-12-11 08:16:01

问题


So, I have two directives, one that has a template file, which contains another directive of the same type.

The first directive looks like:

.directive('billInfo', function () {
    return {
        // scope: true,
        scope: {
            obj: '='
        },
        restrict: 'E',
        templateUrl: 'views/templates/bill-info.html',
        link: function (scope, element, attrs) {
            scope.status = scope.obj.getStatus();
            scope.bill = scope.obj;
        }
    }
})

And the template is pretty simple, something like;

<h4>
  <span class="glyphicon glyphicon-cutlery">
    {{bill.getTable()}}
  </span>
  <small><span class="time"></span></small>
  <div class="btn-group bill-btn">
      <bill-btns billobj="bill"></bill-btns>
  </div>
</h4>

The directive for billBtns looks like:

.directive('billBtns', function () {
    return {
        scope: {
            billobj: '='
        },
        restrict: 'E',
        template: '<div><div>koko{{status}}</div></div>',
        link: function (scope, element, attrs) {
            console.log(scope, scope.billobj);
            scope.status = scope.billobj.getStatus();
        }
    }
})

The problem is unexpected: scope.billobj turns out to be undefined. When I console log scope from within the link function of the billBtns directive, all seems ok: I can see billobj inside scope.

What is going on here? Am I doing something fundamentally wrong here?

EDIT: Template for billInfo

  <div draggable ng-repeat="(index, bill) in getEnq()" bill="bill" id="bill-{{bill.orderCode}}" class="container panel panel-default bill float-{{index%2}}" style="width:300px;" data-created="{{bill.getCreatedOn()}}">
    <bill-info obj="bill"></bill-info>
  </div>

回答1:


I believe I've come to a solution, but I'm uncertain as to if this is the right practice. Here's what the new billBtns directive looks like:

.directive('billBtns', function () {
    return {
        restrict: 'E',
        template: '<div><div>koko{{status}}</div></div>',
        link: function (scope, element, attrs) {
            console.log(scope, scope.$parent.obj);
            scope.status = scope.$parent.bill.getStatus();
        }
    }
})

And that solves the problem. My suspicion is this, if we look at the billInfo directive again, I do something like:

    scope.bill = scope.obj; // woah?

I'd like to understand more about why this happens and why I can access scope.$parent.bill from a nested directive but not scope.$parent.obj without getting typeerrors. Or maybe thats just the way to cascade scopes.



来源:https://stackoverflow.com/questions/22346373/angularjs-objects-inside-nested-directives-getting-undefined

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!