0

I have a service that populates a view data. The view data depends on the data that is fetched from the database and it needs to wait until the data is loaded.

E.g:

services.factory('viewService', function (serviceX) {
    var generateView = function (s) {
        var data=[];
        var viewData=[];
        serviceX.getData().then(function (d) {
            data=d;
        });
        console.log("data:"+d);
        for(x in data){
            viewData[x]=data[x].view;
            ....
        }
        return viewData;
    };
    return{
        generateView: generateView
    }
});

The serviceX.getData() already uses the promise pattern. The line for(x in data){ needs that data to generate the viewData.

3 Answers 3

1

You should use promise to separate concerns :

angular.module('myModule', [])

.factory('Table', function($resource, $q) {
  return {
    data: function() {
      edsql = edsql || '';
      var deferred = $q.defer();
      $resource('my-resource-url').get({}, function(r) {
        deferred.resolve(r);
      }, deferred.reject);

      return deferred.promise;
    }
  };
});

And use it as follows in your controller :

$scope.data = Table.data();
Sign up to request clarification or add additional context in comments.

Comments

0

You can just bind it to your scope variable. AngularJS will wait automatically for the data and then starts rendering. Of course, you need to modify the data that is fetched from within the callback function before setting it on the scope.

In your case this means that your service's generateView method needs to return a promise which you can than set on your scope variable.

Comments

0

Another way is to use deferred & promise.

More info here: http://docs.angularjs.org/api/ng.$q

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.