将一次性绑定应用于自定义元素指令

时间:2015-11-25 19:47:32

标签: javascript angularjs angularjs-directive

我有一个简单的指令 - <call-card> - 而且我想知道如何对其应用一次性绑定,作为优化未来指令的做法。

该指令的定义对象如下:

{
    restrict: 'E',
    controllerAs: 'callCard',
    scope: {
        headline: '=',
        subtitle: '=?',
        highPriority: '=?',
        onFilterClick: '='
    }
}

及其模板:

<div class="headline"
     ng-class="{ 'high-priority': !!callCard.highPriority }">
     {{ callCard.headline }}
</div>
<div class="subtitle"
     ng-if="callCard.subtitle">
     {{ callCard.subtitle }}
</div>
<div class="filter"
     ng-click="callCard.onFilterClick()">
</div>

它的使用方式如下:

<call-card ng-repeat="row in cardList.rows"
           headline="row.headline"
           subtitle="row.subtitle"
           on-filter-click="cardList._.bind(cardList.onFilterRowClick, cardList, row)"></call-card>

集合cardList.rows可能会在cardList中更改,但传递到<call-card>指令的属性在创建<call-card>后永远不会更改。

鉴于这种情况,我应该更改传递到<call-card>的绑定,<call-card>模板中的绑定,还是两者?

例如 - 更改传递到<call-card>的绑定:

<call-card ng-repeat="row in ::cardList.rows"
           headline="::row.headline"
           subtitle="::row.subtitle"
           on-filter-click="::cardList._.bind(cardList.onFilterRowClick, cardList, row)"></call-card>       

例如 - 更改<call-card>模板中的绑定:

<div class="headline"
     ng-class="{ 'high-priority': !!::callCard.highPriority }">
     {{ ::callCard.headline }}
</div>
<div class="subtitle"
     ng-if="::callCard.subtitle">
     {{ ::callCard.subtitle }}
</div>
<div class="filter"
     ng-click="::callCard.onFilterClick()">
</div>

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:0)

也许你需要这个?

app.directive('myOnceBind', function ($parse) {
  return {
    scope: {
      myOnceBind: '='
    },
    link: function ($scope, $element, $attrs) {
      var stopWatch = $scope.$watch(function () {
        return $parse($attrs.myOnceBind)($scope.$parent);
      }, function (n) {
        if (angular.isString(n)) {
          stopWatch();
        }
      });
    }
  }
});

Example

请注意,这仅适用于字符串(您的情况)。