0

I need to call http service once before all templates are loaded ( using ui-routing), and returned data available in all controllers, is that possible?

$http.get('localhost;8080/some.json').then(function(d) {
  return d;
};

1 Answer 1

1

If you want to run it once and make it available to all controllers, then create a service, say, CoreData, and call it from app.run() as follows

app.factory('CoreData',function($http) {
  var data, defer;
  return {
    load: function() {
      defer = $http.get('localhost;8080/some.json');
    },
    get: function() {
        return defer;
    }
  };
})
.controller('CtrlA',function(CoreData) {
   $scope.foo = CoreData.get();
})
.controller('CtrlB',function(CoreData) {
   $scope.foo = CoreData.get();
})
.run(function(CoreData) {
   CoreData.load();
});

If you are concerned about timing, you can do the above .get() as a promise with a single method on CoreData.

To handle the loading, we just pass the $http promise back, which is automatically populated by angular when resolved.

Sign up to request clarification or add additional context in comments.

10 Comments

Just one question: it doesn't work with index.html MainController, it is undefined there.. Is it possible to make it available in that controller for index.html?
I didn't understand that follow on?
I have index.html which has div with ng-view directive for routing. I have header and menu HTML defined in that index.html and I defined main controller for that index.html. I need that json data available in index.html also, because header and menu items are showing from that json also. Do you understand better now?
Is it a timing issue? You could modify all of the above to use promises.
I don't know if it's timing. Index.html uses MainController where I call CoreData.get() but it returns undefined. All other controllers which use templates works like a charm.
|

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.