Set global constants and variables in AngularJs

Using the root scope

// app.js
angular.module('myApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute'
    ])
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    })
    .run(function ($rootScope) {
        $rootScope.mySetting = 42;
    });
// main.js
angular.module('myApp')
    .controller('MainCtrl', [
        '$scope', '$rootScope',
        function ($scope, $rootScope) {
            console.log($rootScope.mySetting);
        }
    ]);

Using the constant method

// app.js
angular.module('myApp', [
        'ngCookies',
        'ngResource',
        'ngSanitize',
        'ngRoute'
    ])
    .constant('config', {
        mySetting: 42
    })
    .config(function ($routeProvider) {
        $routeProvider
            .when('/', {
                templateUrl: 'views/main.html',
                controller: 'MainCtrl'
            })
            .otherwise({
                redirectTo: '/'
            });
    });
// main.js
angular.module('myApp')
    .controller('MainCtrl', [
        '$scope', 'config',
        function ($scope, config) {
            console.log(config.mySetting);
        }
    ]);

1 Comment

  1. cv

    cxcxzsadfdfgsd

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>