繁体   English   中英

Angular Typescript:无法在控制器中注入$ filter

[英]Angular Typescript: Unable to inject $filter in controller

我在指令内使用控制器。 我在控制器构造函数中声明了一个函数(change(searchAttribute:string)),该函数将在内部使用过滤器,但我收到运行时异常“ this。$ filter不是函数”。

我在Google上有很多例子,它们以相同的方式注入$ filter服务,但我无法弄清楚为什么它对我不起作用。

我的代码:

module app.directive {

interface MyDirectiveScope extends ng.IScope {
    myModel: any[];
    change(searchAttribute: string);
}

class MyController {
    static $inject = ['$scope', '$filter'];

    constructor(public $scope: MyDirectiveScope, public $filter: ng.IFilterService) {
        //code

        $scope.change = function (searchAttribute) {
            $scope.myModel = this.$filter('filter')($scope.myModel, searchAttribute); //error : this.$filter turns out to be undefined here
        };
    }
}

class MyDirective implements ng.IDirective {

    static instance(): ng.IDirective {
        return new MyDirective;
    }

    restrict = "E";
    replace = true;
    templateUrl = "myTemplate.html";
    controller = MyController;
    scope = {};
}


angular.module("myModule")
    .directive("myDirective", MyDirective.instance);}

您正在尝试将this用作参考构造函数。 但是,在另一个函数中, this引用用于更改函数,而不是构造函数。 您需要在其他变量(例如self上使用点构造函数。

让我们看一下代码:

constructor(public $scope: MyDirectiveScope, public $filter: ng.IFilterService) {
    let self = this;

    $scope.change = function (searchAttribute) {
        $scope.myModel = self.$filter('filter')($scope.myModel, searchAttribute);
    };
}

您可以使用Typescript箭头函数 this作为上述函数内的类实例上下文:

$scope.change = (searchAttribute) => {
    $scope.myModel = this.$filter('filter')($scope.myModel, searchAttribute);
    // Here, this refers to your class instance context
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM