JohnDizzle JohnDizzle - 3 months ago 5x
Javascript Question

Change of value isn´t persistent between controllers

I´m trying to store some kind of global variable in my application. I read that it´s best practice to use a value instead of a service or a rootscope.

So I created this code snippet to test the behavior of the value. It seems that the value changes indside of the controller but if I use the value in another controller, the change seems to be lost.
Is there a way to change the value during runtime and why is the change not persistant ?

Here is my code on jsfiddle


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

myApp.value("basePath", "");

myApp.controller('TestController', function($scope, basePath) {

$scope.preEdit = basePath;

basePath = window.location.href;
$scope.postEdit = basePath;


myApp.controller('SampleController', function($scope, basePath) {
$scope.transferedValue = basePath;


<div ng-controller="TestController">
Before Editing: {{preEdit}}<br>
After Editing: {{postEdit}}<br>

<div ng-controller="SampleController">
In another Controller: {{transferedValue}}


You'll find an answer in this entry: Global variables in AngularJS

Define the value as an Object

myApp.value("basePath", {value: ""});

After that you can change basePath.value in your controllers.

myApp.controller('TestController', function($scope, basePath) {

    $scope.preEdit = basePath.value;

  basePath.value = window.location.href;
  $scope.postEdit = basePath.value;