As I migrate my project from AngularJS to modern Angular 8, one of the steps is converting JavaScript code to TypeScript. During this process, I encountered a challenging issue with the `ng-repeat` filter feature.
Initially, my HTML template looked like this:
<div ng-repeat="menuItem in items| filter: vm.filterMenuItem">
I found it peculiar that when calling a function, there was no need to specify a passed argument.
Here is the JavaScript code:
function filterMenuItem(menuItem) {
let paramFits = vm.filters.param === 0 || menuItem.param === vm.filters.param;
let anotherParamFits = vm.filters.anotherParam === 0 || menuItem.anotherParam === vm.filters.anotherParam;
return paramFits && anotherParamFits;
}
Where vm.filters
is a controller-level variable that can be modified from the template.
When I rewrote it in TypeScript:
filterMenuItem(menuItem: MenuItemClass) {
let paramFits = this.filters.param === 0 || menuItem.param === this.filters.param;
let anotherParamFits = this.filters.anotherParam === 0 || menuItem.anotherParam === this.filters.anotherParam;
return paramFits && anotherParamFits;
}
...everything broke. AngularJS did not recognize the proper controller-level this
inside the function, resulting in this
being undefined.
Is there a way to maintain a custom filter function with TypeScript?