Rakesh_Kumar Rakesh_Kumar - 7 months ago 22
Javascript Question

Custom filter using app.filter getting called before model is available

I have been trying to add my custom filter to filter out the main list based on locales. To get the main list, I am putting an ajax call. While trying to debug, it looks like

app.filter
seems to execute before the ajax provides the response. Below is the error i am getting:


angular.js:15712TypeError: Cannot read property 'length' of undefined
at messageSelectionCtrl.js:57
at fn (eval at (angular.js:14059), :4:360)
at Object. (angular.js:16730)
at r.$digest (angular.js:18747)
at r.$apply (angular.js:19054)
at g (angular.js:13192)
at T (angular.js:14196)
at XMLHttpRequest.w.onload (angular.js:14364)


Here's a look into the code about what i have been trying to each:

messageSelectionCtrl.js:

//getMessageSelectionConfigs is the service used to make http request and the successhandler and errorhandler defined in controller.
app.controller('messageSelectionCtrl',['$scope','getMessageSelectionConfigs', 'filterData', '$log','errorService', function($scope, getMessageSelectionConfigs, filterData, $log, errorService){

$scope.filterData = filterData;
....
...

//service call to fetch message selection config
getMessageSelectionConfigs.get(data).then(messageSelectionSuccessHandler,messageSelectionErrorHandler);

......
}]);

.......
.....

app.filter('filterByLocale', function(){
return function (messageSelectionList, locale){
var filtered = [];
for (var i=0; i<messageSelectionList.length; i++){
var item= messageSelectionList[i];
if(item.locale === locale){
filtered.push(item);
}
}
return filtered;
};
});

.....
..


messageSelectionTemplate.html

<div ng-repeat = "item in messageSelectionList | filterByLocale: filterData.locale">


mainCtrl.js

app.factory('filterData', function(){
return {
locale : ''
};
});


the
messageSelectionSuccessHandler
function executes after the error comes. This is weird because view should be triggered once ng-repeat has some model to loop in.
Please let me know what i am missing or any pointers would be helpful.

Answer

Initialise messageSelectionList = [] first so its never undefined. The loop will update with data once fetched.

And to ignore empty filters -

app.filter('filterByLocale', function(){
  return function (messageSelectionList, locale){
    if(locale){
      var filtered = [];
      for (var i=0; i<messageSelectionList.length; i++){
      var item= messageSelectionList[i];
      if(item.locale === locale){
         filtered.push(item);
       }
     return filtered;
    }
    return messageSelectionList
  }
  };
});
Comments