Reputation: 1
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) {
//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);}
Upvotes: 0
Views: 2964
Reputation: 1384
You can use Typescript arrow functions to have this
as the class instance context inside the aforesaid function:
$scope.change = (searchAttribute) => {
$scope.myModel = this.$filter('filter')($scope.myModel, searchAttribute);
// Here, this refers to your class instance context
};
Upvotes: 2
Reputation: 4286
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);
};
}
Upvotes: 1