【问题标题】:Angular Call NGIF inside custom directive自定义指令中的 Angular 调用 NGIF
【发布时间】:2017-02-11 21:01:43
【问题描述】:

我希望在我自己的指令中使用 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);。这里没有 apply 方法。

【问题讨论】:

  • 您想要的最终结果到底是什么? sn-p 您发现它非常hacky,并且可能有一种更清洁的方式来做您想做的事情。上面的代码正在深入挖掘底层框架,对其进行假设,并尝试将其完全编织成其他东西。
  • 基本上我想创建我自己的我的 if 指令。我的指令将与角度服务商交谈以确定结果。我认为创建一个围绕 ngif 指令的包装器会更容易和未来证明。

标签: angularjs typescript angularjs-directive


【解决方案1】:

我不推荐扩展指令。没有一个好的方法可以做到这一点,每个指令处理模板、嵌入和范围的方式会有所不同,并且不太可能网格化。

如果你想包装一个指令,我建议使用嵌入并正常使用该指令。

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>

【讨论】:

  • 我最终走上了这条路。转换为 Typescript 要容易得多。谢谢
猜你喜欢
  • 2019-07-23
  • 1970-01-01
  • 2021-05-15
  • 2019-01-27
  • 1970-01-01
  • 2018-06-24
  • 1970-01-01
  • 2017-06-29
  • 1970-01-01
相关资源
最近更新 更多