ankush singla ankush singla - 1 year ago 64
TypeScript Question

Angular Typescript: Unable to inject $filter in controller

I am using a controller inside my directive. I have declared a function (change(searchAttribute: string)) in controller constructor which will internally use the filter but i am getting runtime exception "this.$filter is not a function".

I have got many examples on google which injects $filter service the same way but i am unable to figure out why it is not working for me.

My code :

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) {

$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 = {};

.directive("myDirective", MyDirective.instance);}

Answer Source

You are trying to use this for reference constructor. But, inside an another function, this reference to change function and not the constructor. You need point contructor before on another variable, like self.

Lets go to the code:

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

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