Global Variables in 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 )

var app = angular.module('appName',);
//Add this to have access to a global variable
app.run(function ($rootScope) {
    $rootScope.globalVariable = 'Hi, global variabel'; //global variable
});

Now if you want to use it from your controller

function appNameCtrl($scope, $rootScope){
    $rootScope.globalVariable = 'Modji';
}

In your view

My name is {{globalVariable}}

If you are using any services like $http in your controller then you have to pass $rootScope as service along with $http.

app.controller('appNameCtrl', ['$http', '$rootScope', function ($scope, $rootScope){
    $rootScope.globalVariable = 'Modji';

}]);


To see the example visit my Plunker at http://plnkr.co/edit/JyIfkT1AxiCU2xx4WjJK?p=preview

This post is edited and was originally published at Coding Insight.
Share your love
Muhammad Jawaid Shamshad
Muhammad Jawaid Shamshad
Articles: 128

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.