198

宣言されている要素にさらにディレクティブを追加するディレクティブを作成しようとしています。たとえば、datepicker,datepicker-languageng-required="true".

これらの属性を追加してから使用しようとすると、$compile明らかに無限ループが発生するため、必要な属性が既に追加されているかどうかを確認しています。

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        element.attr('datepicker', 'someValue');
        element.attr('datepicker-language', 'en');
        // some more
        $compile(element)(scope);
      }
    };
  });

もちろん、$compile要素を指定しない場合、属性は設定されますが、ディレクティブはブートストラップされません。

このアプローチは正しいですか、それとも間違っていますか? 同じ動作を実現するためのより良い方法はありますか?

UDPATE :$compileこれを達成する唯一の方法であるという事実を考えると、最初のコンパイル パスをスキップする方法はありますか (要素には複数の子が含まれる場合があります)。多分設定でterminal:true

更新 2 :ディレクティブを要素に入れようとしましたがselect、予想どおり、コンパイルが 2 回実行されます。これは、予想される s の数が 2 倍であることを意味しoptionます。

4

7 に答える 7

264

1 つの DOM 要素に複数のディレクティブがあり、それらが適用される順序が重要な場合は、priorityプロパティを使用してそれらの適用を順序付けることができます。数値が大きいほど最初に実行されます。指定しない場合、デフォルトの優先度は 0 です。

編集:議論の後、ここに完全な実用的なソリューションがあります。キーは、属性を削除することでした: element.removeAttr("common-things");、およびelement.removeAttr("data-common-things");(ユーザーdata-common-thingsがhtmlで指定した場合)

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false, 
      terminal: true, //this setting is important, see explanation below
      priority: 1000, //this setting is important, see explanation below
      compile: function compile(element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        return {
          pre: function preLink(scope, iElement, iAttrs, controller) {  },
          post: function postLink(scope, iElement, iAttrs, controller) {  
            $compile(iElement)(scope);
          }
        };
      }
    };
  });

ワーキング プランカーはhttp://plnkr.co/edit/Q13bUt?p=previewで入手できます。

または:

angular.module('app')
  .directive('commonThings', function ($compile) {
    return {
      restrict: 'A',
      replace: false,
      terminal: true,
      priority: 1000,
      link: function link(scope,element, attrs) {
        element.attr('tooltip', '{{dt()}}');
        element.attr('tooltip-placement', 'bottom');
        element.removeAttr("common-things"); //remove the attribute to avoid indefinite loop
        element.removeAttr("data-common-things"); //also remove the same attribute with data- prefix in case users specify data-common-things in the html

        $compile(element)(scope);
      }
    };
  });

デモ

terminal: trueand priority: 1000(高い数値)を設定する必要がある理由の説明:

priority DOM の準備ができると、angular は DOM をウォークして、登録されているすべてのディレクティブを識別し、これらのディレクティブが同じ要素にあるかどうかに基づいて、ディレクティブを 1 つずつコンパイルします。カスタム ディレクティブの優先順位を高い数値に設定して、それが最初にコンパイルされるようにし、このディレクティブがコンパイルされた後terminal: trueに他のディレクティブがスキップされるようにします。

カスタム ディレクティブがコンパイルされると、ディレクティブを追加してそれ自体を削除することで要素を変更し、$compile サービスを使用してすべてのディレクティブ (スキップされたものを含む) をコンパイルします

と を設定しないterminal:trueと、カスタム ディレクティブの前にpriority: 1000いくつかのディレクティブがコンパイルされる可能性があります。そして、カスタム ディレクティブが $compile を使用して要素をコンパイルする場合 => 既にコンパイルされたディレクティブを再度コンパイルします。特に、カスタム ディレクティブの前にコンパイルされたディレクティブが既に DOM を変換している場合は、予期しない動作が発生します。

優先度と端末の詳細については、ディレクティブの `端末` を理解する方法は? を参照してください。

テンプレートも変更するディレクティブの例はng-repeat(priority = 1000) で、ng-repeatコンパイル時ng-repeat に、他のディレクティブが適用される前にテンプレート要素のコピーを作成します

@Izhaki のコメントのおかげで、ngRepeatソース コードへの参照は次のとおりです: https://github.com/angular/angular.js/blob/master/src/ng/directive/ngRepeat.js

于 2013-10-07T15:06:32.903 に答える
6

これは、動的に追加する必要があるディレクティブをビューに移動し、オプションの (基本的な) 条件付きロジックを追加するソリューションです。これにより、ハードコーディングされたロジックを使用せずに、ディレクティブがクリーンに保たれます。

ディレクティブはオブジェクトの配列を受け取ります。各オブジェクトには、追加するディレクティブの名前とそれに渡す値 (存在する場合) が含まれます。

このようなディレクティブのユースケースを考えるのに苦労していましたが、何らかの条件に基づいてディレクティブを追加するだけの条件付きロジックを追加すると便利かもしれないと思いました (ただし、以下の答えはまだ考案されています)。ifディレクティブを追加する必要があるかどうかを決定する bool 値、式、または関数 (コントローラーで定義されているなど) を含む必要があるオプションのプロパティを追加しました。

また、チェックする文字列値をハードコーディングせずに、ディレクティブ (例: )をattrs.$attr.dynamicDirectives追加するために使用される正確な属性宣言を取得するためにも使用しています。data-dynamic-directivedynamic-directive

Plunker Demo

angular.module('plunker', ['ui.bootstrap'])
    .controller('DatepickerDemoCtrl', ['$scope',
        function($scope) {
            $scope.dt = function() {
                return new Date();
            };
            $scope.selects = [1, 2, 3, 4];
            $scope.el = 2;

            // For use with our dynamic-directive
            $scope.selectIsRequired = true;
            $scope.addTooltip = function() {
                return true;
            };
        }
    ])
    .directive('dynamicDirectives', ['$compile',
        function($compile) {
            
             var addDirectiveToElement = function(scope, element, dir) {
                var propName;
                if (dir.if) {
                    propName = Object.keys(dir)[1];
                    var addDirective = scope.$eval(dir.if);
                    if (addDirective) {
                        element.attr(propName, dir[propName]);
                    }
                } else { // No condition, just add directive
                    propName = Object.keys(dir)[0];
                    element.attr(propName, dir[propName]);
                }
            };
            
            var linker = function(scope, element, attrs) {
                var directives = scope.$eval(attrs.dynamicDirectives);
        
                if (!directives || !angular.isArray(directives)) {
                    return $compile(element)(scope);
                }
               
                // Add all directives in the array
                angular.forEach(directives, function(dir){
                    addDirectiveToElement(scope, element, dir);
                });
                
                // Remove attribute used to add this directive
                element.removeAttr(attrs.$attr.dynamicDirectives);
                // Compile element to run other directives
                $compile(element)(scope);
            };
        
            return {
                priority: 1001, // Run before other directives e.g.  ng-repeat
                terminal: true, // Stop other directives running
                link: linker
            };
        }
    ]);
<!doctype html>
<html ng-app="plunker">

<head>
    <script src="//code.angularjs.org/1.2.20/angular.js"></script>
    <script src="//angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.6.0.js"></script>
    <script src="example.js"></script>
    <link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
</head>

<body>

    <div data-ng-controller="DatepickerDemoCtrl">

        <select data-ng-options="s for s in selects" data-ng-model="el" 
            data-dynamic-directives="[
                { 'if' : 'selectIsRequired', 'ng-required' : '{{selectIsRequired}}' },
                { 'tooltip-placement' : 'bottom' },
                { 'if' : 'addTooltip()', 'tooltip' : '{{ dt() }}' }
            ]">
            <option value=""></option>
        </select>

    </div>
</body>

</html>

于 2014-07-17T02:51:55.873 に答える
1

次のように、要素自体の属性に状態を保存してみてください。superDirectiveStatus="true"

例えば:

angular.module('app')
  .directive('superDirective', function ($compile, $injector) {
    return {
      restrict: 'A',
      replace: true,
      link: function compile(scope, element, attrs) {
        if (element.attr('datepicker')) { // check
          return;
        }
        var status = element.attr('superDirectiveStatus');
        if( status !== "true" ){
             element.attr('datepicker', 'someValue');
             element.attr('datepicker-language', 'en');
             // some more
             element.attr('superDirectiveStatus','true');
             $compile(element)(scope);

        }

      }
    };
  });

これがお役に立てば幸いです。

于 2013-10-07T11:51:37.780 に答える