Search code examples
javascriptangularjsangular-filters

Filter not working after refreshing the page


I have this input search

<input type="search" ng-model="query">

<div ng-repeat="sport in sports | filter:query"></div>

which is working awesome after the user logs in, but within the same session if the user refreshes the page, the filter doesn't work anymore, if you type something in the search box, nothing happens, the array doesn't change.

this is the service

angular.module('myApp.services')
  .factory('SportsFactory', function($http, $q,
    AuthFactory, LeaguesFactory, LocalForageFactory, CONSTANT_VARS) {

return {
      getSportsWithLeagues: function(customer) {
        var _this = this,
            defer = $q.defer(),
            rejection = function(err) {
              defer.reject(err);
            },
            sportsLength;

        LocalForageFactory.retrieve(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES)
          .then(function(sportLeagues) {
            if (!_.isNull(sportLeagues)) {
              defer.resolve(sportLeagues);
            }else {
              _this.getSports(customer.agent).then(function(sports) {
                sportsLength = sports.length;
                LeaguesFactory.getLeagues({
                  sportIds: _.pluck(sports, 'id'),
                  lineProfile: customer.lineProfile,
                  betLimit: customer.betLimit
                }).then(function(leagues) {
                  _.each(sports, function(sport) {
                    sport.leagues = _.filter(leagues, function(league) {
                      return sport.id === league.sport.id;
                    });
                  });
                  LocalForageFactory.set(CONSTANT_VARS.LOCALFORAGE_SPORTS_LEAGUES, sports);
                  defer.resolve(sports);
                }, rejection);

              }, rejection);
            }
          }, rejection);
        return defer.promise;
      }
   }
}

and here a part of the controller

angular.module('myApp.controllers', [])
  .controller('LinesCtrl', function($scope, customer,
               SportsFactory, LinesFactory) {

  $scope.query = '';
  SportsFactory.getSportsWithLeagues(customer).then(function(sports) {
    $scope.sports = sports;
  });
}

I also have this $watch

$scope.$watch('query', function(val) {
   console.log(val);
});

to check if the filter stops working after refreshing, but still works properly and you can see the logs in the console every time you type something in the finder.

So, what do you think is happening here ?


Solution

  • the issue is that every time you are refreshing the page, in the promise sportLeagues is returning an object, only an object with some other objects inside, as you are using lodash, just put defer.resolve(_.values(sportLeagues)); and that will be enough to return the values that you need. Tell me if you need to know something else