2016-10-03 65 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