1

Suppose my web app needs to make a http request to get my site title, site description and so on. Since these variables are common to all pages, it makes sense to request those every time a user enter the site.

The question is, where do I make those calls? In run block? Or to create a root controller to do these tasks?

1
  • I think, you can use root ( or main ) controller Commented Apr 19, 2016 at 3:20

2 Answers 2

3

You can use one of these two approaches:

  1. Make your call in run block and store the value in $rootScope and use anywhere you want,
  2. In your states, use resolve to get the page title and details , and get it in the views , For ease use resolve in root state and use the resolved variable as a dependency in other child or sibling routes to get values..

        $stateProvider.state('root', {
          resolve:{
    
            // Example using function with simple return value.        
            promiseObj:  function($http){
            // $http returns a promise for the url data
            return $http({method: 'GET', url: '/someUrl'});
          }
        })
       .state('sibling',{
         controller:function($scope,promiseObj){
          $scope.title = promiseObj.title;
         }
        })
    
Sign up to request clarification or add additional context in comments.

Comments

0

You could define controller at the <html> level.

 <html ng-app="app" ng-controller="initCtrl">
   <head>
     <title>{{ Page.title() }}</title>
 ...

You create service: Page and modify from controllers.

myModule.factory('Page', function() {
   var title = //Code to get the title
   .... //Other vars
   return {
     title: function() { return title; },
     setTitle: function(newTitle) { title = newTitle }
     ...
   };
});

Inject Page and Call 'Page.setTitle()' from controllers.

Comments

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.