Thursday, March 28, 2013

Global variable with AngularJS - Coding Insight

Global variable with AngularJS - Coding Insight


Global variable with AngularJS

I’ve followed the angularjs tutorial and I noticed that I wasn’t able to have global variables.
Turns out to be actually simple but Angular doesn’t mention it.
You will need to edit your app module (app.js )
1
2
3
4
5
6
7
8
9
10
11
12
var app = angular.module('appName',).
    config(['$routeProvider', function($routeProvider){
        $routeProvider.
            when('/index', {templateUrl: 'list.html', controller: appNameCtrl}).
            when('/:catId/', { templateUrl: 'categorylist.html', controller: categoryCtrl }).
            otherwise({redirectTo: '/index'});
} ]);
 
//Add this to have access to a global variable
app.run(function ($rootScope) {
    $rootScope.globalVariable = 'Amadou'; //global variable
});
Now if you want to use it from your controller
1
2
3
function appNameCtrl($scope, $rootScope){
    $rootScope.globalVariable = 'Modji';
}
In you view
1
My name is {{globalVariable}}

No comments: