2016-10-03 7 views
0

自分のディレクティブ内でNGIFを一種のラッパーとして使用しようとしています。Angular Callカスタムディレクティブ内のNGIF

私はこの問題は、私はこれが活字体に変換する方法がわからないです

var NAME = 'yourCustomIf'; 

angular.module('myApp', []) 
.directive(NAME, function (ngIfDirective) { 
    console.log(ngIfDirective) 

    var ngIf = ngIfDirective[0]; 

    return { 
     transclude: ngIf.transclude, 
     priority: ngIf.priority, 
     terminal: ngIf.terminal, 
     restrict: ngIf.restrict, 
     link: function ($scope, $element, $attr) { 
      var value = $attr[NAME]; 
      var yourCustomValue = $scope.$eval(value); 

      $attr.ngIf = function() { 
       return yourCustomValue; 
      }; 


      ngIf.link.apply(ngIf, arguments); 
     } 
    }; 

}); 

...完璧に働いている、次の例を見つけました。ここに私がこれまで持っているものがあります...

export class MyCustomDirective implements ng.IDirective { 

    constructor(private ngIfDirective: ng.IDirective) { 

    } 

    transclude = this.ngIfDirective.transclude; 
    priority = this.ngIfDirective.priority; 
    terminal = this.ngIfDirective.terminal; 
    restrict = this.ngIfDirective.restrict; 

    link = (scope: ng.IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctrl: any) => { 

     var atrribute = attrs["custom"]; 

     var value = scope.$eval(atrribute); 

     attrs["ngIf"] =() => { 
      return value; 
     }; 


    } 

} 

私の問題は最終行ngIf.link.apply(ngIf, arguments);です。適用方法はありません。

+0

? あなたはそれが非常にハッキーであることを発見したスニペットで、おそらくあなたが望むことを行うためのきれいな方法があります。上のコードは、基礎となるフレームワークを深く掘り下げ、前提を作り、それを他のものに完全に編み込もうとしています。 – Enzey

+0

基本的に自分のmy if指令を作成したいと思います。私の指示は、結果を決定するために角度のあるサービスと話すつもりです。 ngifディレクティブの周りにラッパーを作成する方が簡単で、将来の証明ができると思いました。 – fml

答えて

2

ディレクティブを拡張することはお勧めできません。それを行うには良い方法はなく、各ディレクティブがテンプレート、トランジション、スコープを処理する方法が異なり、メッシュしない可能性があります。

ディレクティブをラップしたい場合は、transclusionを使用し、ディレクティブを通常通り使用することをお勧めします。

module.directive('specialIf', function (myService) { 
    return { 
     transclude: true, 
     scope: {}, 
     template: '<ng-transclude ng-if="isShown"></ng-transclude>' 
     link: function (scope, element, attr) { 
      scope.isShown = myService.isShown(); 
     } 
    }; 

}); 

ご使用方法は、次のようになります。ご所望の最終結果である正確に何

<special-if> 
    <div>Stuff I may or may not want showing up</div> 
</special-if> 
+0

私はこのルートを下りてしまった。 Typescriptに変換する方がはるかに簡単でした。ありがとうございました – fml

関連する問題