2016-10-03 70 views
0

我期待在我自己的指令中使用NGIF作爲一種包裝。角度調用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

基本上我想創建我自己的我的我的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