0

Using AngularJS 1.0.4

One of our Angular apps is dependent on a resource being loaded before anything else can be loaded. We do this from a service that gets initialized in app.run() and then broadcast an event that everything else listens for to start loading.

In the controllers we also need to have access to the resulting resource. So I then have the following in each one:

$scope.parent = null;

if(!svc.parent) {
  $scope.on('parentLoaded', function() {
    $scope.parent = svc.parent;
  });
} else {
  $scope.parent = svc.parent;
}

Each of the controllers is tied to a view and can be called in any order. So it's not guaranteed that the resource is loaded when the controller gets called, although it can be if another controller was called before hand. The load event only gets trigger the first time the service is initialized when the app first loads.

Is there a better way to this?

It seems kind of redundant & not clean.

2 Answers 2

2

I would just use a promise. You would have something like:

var deferred = $q.defer();
$http.get('/application').then(function(res) {
    deferred.resolve(res);
});
function fetch() {
  return deffered.promise;
}

To load your initial resource, we'll call the resource "application" for example. Then, to load your next portion, you can do:

application.fetch().then(function(svc) {
  //res is whatever is returned from our $http.get, earlier
  $scope.parent = svc.parent
  //do whatever required your resource here
});
Sign up to request clarification or add additional context in comments.

Comments

0

Instead of doing this:

$scope.parent = null;

Create an empty array instead (or object depending on what resource is).

$scope.parent = [];

This way angular object watchers will react to changes of the array. For more advanced issues can use promises when loading data

3 Comments

It's not a collection, it's an object & the fact that it might be null means something to the application.
sounds like you need to implement return of promises then from the service. Then you can cache the original load if it took place and resolve promise with that data, or make the call to load if data isn't caached and resolve the promise when data returns from server
$http also has caching ability , set cache:true in config docs.angularjs.org/api/ng.$http and return the whole request to controller, use then callback to set your scope value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.