Angularjs:嵌套指令中的物体变得不确定



所以,我有两个指令,一个具有模板文件,其中包含同一类型的另一个指令。

第一个指令看起来像:

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

,模板很简单,类似;

<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>

billbtns的指令看起来像:

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

问题是出乎意料的:范围。当我从BillBTNS指令的链接函数内部控制log scope 时,一切似乎都可以:我可以在范围内看到Billobj。

这里发生了什么?我在这里从根本上做错了吗?

编辑: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>

我相信我已经提出了一个解决方案,但是我不确定这是正确的做法。这是新的BillBTNS指令的样子:

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

这解决了问题。我的怀疑是,如果我们再次查看Billinfo指令,我会做类似的事情:

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

我想更多地了解为什么会发生这种情况以及为什么我可以访问范围。也许那就是通往级联范围的方式。

最新更新