デフォルトオプション付きのAngularJSディレクティブ 質問する

デフォルトオプション付きのAngularJSディレクティブ 質問する

私は AngularJS を使い始めたばかりで、いくつかの古い jQuery プラグインを Angular ディレクティブに変換する作業を行っています。属性でオプション値を指定してオーバーライドできる、(要素) ディレクティブのデフォルト オプションのセットを定義したいと思います。

私は他の人がこれをどうやってやっているか調べましたが、角度UI図書館ui.bootstrap.ページネーション似たようなことをしているようです。

まず、すべてのデフォルト オプションが定数オブジェクトで定義されます。

.constant('paginationConfig', {
  itemsPerPage: 10,
  boundaryLinks: false,
  ...
})

次に、getAttributeValueユーティリティ関数がディレクティブ コントローラにアタッチされます。

this.getAttributeValue = function(attribute, defaultValue, interpolate) {
    return (angular.isDefined(attribute) ?
            (interpolate ? $interpolate(attribute)($scope.$parent) :
                           $scope.$parent.$eval(attribute)) : defaultValue);
};

最後に、これはリンク関数で属性を読み込むために使用されます。

.directive('pagination', ['$parse', 'paginationConfig', function($parse, config) {
    ...
    controller: 'PaginationController',
    link: function(scope, element, attrs, paginationCtrl) {
        var boundaryLinks = paginationCtrl.getAttributeValue(attrs.boundaryLinks,  config.boundaryLinks);
        var firstText = paginationCtrl.getAttributeValue(attrs.firstText, config.firstText, true);
        ...
    }
});

これは、デフォルト値のセットを置き換えたいという標準的なこととしては、かなり複雑な設定のように思えます。これを行う一般的な方法は他にもありますか? または、常に などのユーティリティ関数を定義しgetAttributeValue、このようにオプションを解析するのが普通ですか? この一般的なタスクに対して、人々がどのような異なる戦略を持っているかを知りたいと思っています。

また、おまけに、なぜパラメータinterpolateが必要なのかがよくわかりません。

ベストアンサー1

=?ディレクティブのスコープ ブロック内のプロパティのフラグを使用します。

angular.module('myApp',[])
  .directive('myDirective', function(){
    return {
      template: 'hello {{name}}',
      scope: {
        // use the =? to denote the property as optional
        name: '=?'
      },
      controller: function($scope){
        // check if it was defined.  If not - set a default
        $scope.name = angular.isDefined($scope.name) ? $scope.name : 'default name';
      }
    }
  });

おすすめ記事