Typescript as custom ng-repeat filter not working as expected
module ngrFilter{
'use strict';
export class UsersCtrl {
public userCollection: any[];
public userFilter: string;
constructor(){
this.userCollection = [{id:1,name:'John',surname:'Klopper'},
{id:2,name:'Mary',surname:'Schoeman'}];
}
public filterUser(user){
//The this is undefined when using as a custom filter for ng-repeat
console.log(this.userFilter)
if(user.name == this.userFilter ||
user.surname == this.userFilter){
return true;
}
}
}
angular
.module('ngrFilter',[])
.controller('UsersCtrl', UsersCtrl);
}
When using a custom filter for ng-repeat, the property this
is undefined in the filterUser method. Is there a way to make this filter work or am I just doing something stupid.
I also tried adding sample code here: http://fiddlesalad.com/typescript/custom-ngrepeat-filter/
+3
source to share
2 answers
Instead of a method, use a public field as a filter function that can create a closure for this.
export class UsersCtrl {
public userCollection: any[];
public userFilter: string;
public filterUser: (User) => boolean;
constructor(){
this.userCollection = [{id:1,name:'John',surname:'Klopper'},
{id:2,name:'Mary',surname:'Schoeman'}];
var self = this;
this.filterUser = function(user:User) {
return self./*...*/;
}
}
}
+5
source to share
What you are trying to do can be accomplished with angular filter
For what you are trying to do I will just handle the event and recheck the list when the filter changes
export class UsersCtrl {
public userCollection: any[];
public filteredUserCollection: any[];
public userFilter: string;
constructor(){
this.userCollection = [{id:1,name:'John',surname:'Klopper'},
{id:2,name:'Mary',surname:'Schoeman'}];
this.filteredUserCollection = this.userCollection;
}
public filterChanged(filter){
this.filterUser(filter);
}
public filterUser(filter){
var results = [];
if(user.name == filter ||
user.surname == filter){
results.push(user);
}
this.filteredUserCollection = results;
}
}
And then your markup will change to:
<input ng-model="users.userFilter" ng-change="users.filterChanged(users.userFilter)">
<ul>
<li ng-repeat="user in users.filteredUserCollection">
{{user.name}} {{user.surname}}
</li>
</ul>
0
source to share