Reputation: 372
I have created an AngularJS filter that is working very awesome !!! but the problem with the console. in console, showing error though it is working. now i want to remove the error.
this is error in console:
TypeError: Cannot read property 'sort' of undefined
at filter.js:14
here you go for my filter:
app.filter('filterByName', function () {
return function (item) {
return item.sort((a,b) => a.name.localeCompare(b.name))
};
});
Note again, the filter is working fine but only it showing this error in console, my concern with this error.
this is how i used this filter in tempalate:
<tr ng-repeat="contact in contacts | filterByName track by $index ">
I heard of the error is showing coz, i didnt configure the js version but i dont know what is this and how to do it.
can anyone tell me how can i get rid of this problem?
Optional:
this is where i initialized Contacts.
$scope.getAllContact = function() {
var data = $http.get("http://127.0.0.1:8000/api/v1/contact/")
.then(function(response) {
$scope.contacts = response.data;
}, function(response) {
});
};
Upvotes: 1
Views: 85
Reputation: 4448
You are getting that error because your item is undefined, you can add the following lines to prevent that error.
app.filter('filterByName', function () {
return function (item) {
if(item == undefined)
item = []
return item.sort((a,b) => a.name.localeCompare(b.name))
};
});
You can also initialise $scope.contacts = [] in your controller to avoid this issue.
Upvotes: 1