Angularjs 角度调用NGIF内部自定义指令
我希望在我自己的指令中使用NGIF作为一种包装器 我发现下面的例子非常有效Angularjs 角度调用NGIF内部自定义指令,angularjs,typescript,angularjs-directive,Angularjs,Typescript,Angularjs Directive,我希望在我自己的指令中使用NGIF作为一种包装器 我发现下面的例子非常有效 var NAME = 'yourCustomIf'; angular.module('myApp', []) .directive(NAME, function (ngIfDirective) { console.log(ngIfDirective) var ngIf = ngIfDirective[0]; return { transclude: ngIf.transclu
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);
}
};
});
问题是我不知道如何将其转换为typescript。这是我到目前为止所拥有的
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)代码>。这里没有应用方法。我不能推荐扩展指令。没有一个好的方法可以做到这一点,而且每个指令处理模板、转换和作用域的方式将不同,并且不太可能相互匹配
如果您想包装一个指令,我建议使用转换,并像正常情况一样使用该指令
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();
}
};
});
module.directive('specialIf',function(myService){
返回{
是的,
作用域:{},
模板:“”
链接:功能(范围、元素、属性){
scope.isShown=myService.isShown();
}
};
});
您的使用情况如下所示:
<special-if>
<div>Stuff I may or may not want showing up</div>
</special-if>
我可能不想出现的东西
我不能建议扩展指令。没有一个好的方法可以做到这一点,而且每个指令处理模板、转换和作用域的方式将不同,并且不太可能相互匹配
如果您想包装一个指令,我建议使用转换,并像正常情况一样使用该指令
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();
}
};
});
module.directive('specialIf',function(myService){
返回{
是的,
作用域:{},
模板:“”
链接:功能(范围、元素、属性){
scope.isShown=myService.isShown();
}
};
});
您的使用情况如下所示:
<special-if>
<div>Stuff I may or may not want showing up</div>
</special-if>
我可能不想出现的东西
您希望的最终结果是什么?你发现这段代码非常粗糙,可能有一种更干净的方法来做你想做的事情。上面的代码正在深入挖掘底层框架,对其进行假设,并试图将其完全编入其他内容。基本上,我想创建自己的if指令。我的指令将与一个角度服务进行对话,以确定结果。我认为围绕ngif指令创建一个包装器会更容易,也更符合未来的需要。您希望的最终结果是什么?你发现这段代码非常粗糙,可能有一种更干净的方法来做你想做的事情。上面的代码正在深入挖掘底层框架,对其进行假设,并试图将其完全编入其他内容。基本上,我想创建自己的if指令。我的指令将与一个角度服务进行对话,以确定结果。我认为围绕ngif指令创建一个包装器会更容易,也更符合未来的需要。转换成Typescript要容易得多。谢谢你,我最后选择了这条路线。转换成Typescript要容易得多。非常感谢。