1

假设我已经实现了一个指令,如下所示:

module.directive("foo", function($scope) {
      return {
          controllerAs: "model",
          controller: function($scope) {
              this.items = $scope.items;

              this.selectItem = function(item) {
                   this.selectedItem = item;
              };
          },
          scope: { items: "=" }
      };
});

module.directive("bar", function($scope) {
      return {
          controllerAs: "model",
          controller: function() { 
               this.item = $scope.item;
          },
          scope: { item: "=" }
      };
});

...其中foo指令的模板如下所示:

<bar item="model.selectedItem" />
<ol>
<li ng-repeat="item in model.items" ng-click="model.selectItem(item)">
    <bar item="item" />
</li>
</ol>

...和bar指令的模板看起来像:

<span ng-bind="item.text"></span>

TL;DR:我的问题

model.selectedItem因为用户点击了一些重复 <bar />而发生变化时,外部<bar />不知道任何所谓的属性变化。也就是说,外部<bar />不会更新其绑定model.text属性。

我不明白为什么foo's 控制器上的模型更改不会更改外部bar指令。

4

1 回答 1

1

selectedItem位于foo指令范围内。因此,它不会对外部可见(bar指令)。

您可以保留另一个包含所选项目键的变量。然后在bar指令中,您可以按如下方式绑定值,

<bar item ="items[selectedKey].text"></bar>

编辑:您也可以尝试在范围上设置值而不是在this.

$scope.selectedItem = item;

代替

this.selectedItem = item; 
于 2016-05-03T11:16:03.603 回答