mindparse
mindparse

Reputation: 7235

Setting AngularJS global values for accessing and setting across controllers

I have been experimenting with AngularJS values, and wish to store a global value for accessing and setting in different controllers.

So I have been trying out with the value approach like so:

var app = angular.module('myApp', []);

app.value('globalValue', 0);

app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
    $scope.updateValue = function() {
        globalValue++;
    };    
}]);

app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
        $scope.someValueB=globalValue;

}]);

Here's a fiddle

This is not working as I thought it might, so in my fiddle, when clicking the button to increment my 'global', the scope property in myCtrlB does not change.

I have clearly gone about this the wrong way, have I totally misunderstood how to use value()'s here?

Thanks

Upvotes: 0

Views: 1311

Answers (1)

shaunhusain
shaunhusain

Reputation: 19748

This code should work basically you need an object so both controllers are pointing at the same object and some property of that object is changed. Otherwise you are assigning the initial value of globalValue to some local variable but it's not a reference.

var app = angular.module('myApp', []);

app.value('globalValue', {counter:0});

app.controller('myCtrl', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
    $scope.updateValue = function() {
        globalValue.counter++;
    };    
}]);

app.controller('myCtrlB', ['$scope', '$rootScope', 'globalValue', function($scope, $rootScope, globalValue) {
        $scope.someValueB=globalValue;

}]);

Updated fiddle: http://jsfiddle.net/kfxy5hs1/3/

Upvotes: 2

Related Questions