Mike Glaz
Mike Glaz

Reputation: 5382

waiting for $http.get call to complete

I know this has something to do with promises but I'm having a hard time understanding how to implement them.

My controller:

angular.module('landingApp')
  .controller('MainCtrl', function($http, $q){
    var main = this;

    main.favoritesIds = [];

    $http.get('api/v1/planograms/get_favorites')
      .success(function(data){
        for(var i=0; i < data.planograms.length; i++)
          main.favoritesIds.push(data.planograms[i].id);
      });

    main.isFavorite = function(planogram_id){
      return main.favoriteIds.indexOf(planogram_id) > -1;
    };

then in my template I use isFavorite() like this:

<div class="col-md-6" ng-repeat="planogram in main.planograms">
  <i class="fa fa-star fa-2x favorite" ng-class="{'yellow' : main.isFavorite(planogram.id)}">

So basically I want the star icons turned yellow for all planograms marked 'favorite'. But main.isFavorite() returns undefined I'm guessing because the $http.get method has not resolved. So my question is how would I implement promises in this situation?

Upvotes: 1

Views: 723

Answers (1)

New Dev
New Dev

Reputation: 49590

First of all, it doesn't work because you have a typo in isFavorite function: it is not main.favoriteIds, but main.favoritesIds.

Second, it should work regardless of promises. You are right that before the $http call is returned, the main.favoritesIds is empty, but when it is filled, the array becomes populated, and the isFavorite function (being watched by Angular) is re-evaluated.

Although your code would work once the typo is fixed, it is not optimal. Watched functions are called on every digest cycle, and should be blazing fast, whereas your isFavorite does isIndexOf, which has O(n) complexity.

Instead of creating an array of favoritesIds, create an object, such that you could do an O(1) lookup. Or, better yet, augment the planograms array with favorite data.

For example, with favoritesIds as an object:

 $http.get('api/v1/planograms/get_favorites')
    .success(function(data){
        for(var i=0; i < data.planograms.length; i++) {
          main.favoritesIds[data.planograms[i].id] = true;
        }
    });

 main.isFavorite = function(planogram_id){
   return main.favoritesIds[planogram_id];
 };

Upvotes: 2

Related Questions