2

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

Javascript

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;
})

HTML:

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

<div ng-controller="SampleController">
  In another Controller: {{transferedValue}}
</div>
JohnDizzle
  • 1,268
  • 3
  • 24
  • 51

4 Answers4

4

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;

});
Community
  • 1
  • 1
Benjamin Schüller
  • 2,104
  • 1
  • 17
  • 29
1

use a constant,

myApp.constant( 'basePath', '' );

this will allow you to inject the value into modules.

fayzaan
  • 265
  • 3
  • 9
0

Here's is a snippet working:

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

app.controller('TestController', function($scope, $rootScope) {
  $rootScope.postEdit = window.location.href;
});

app.controller('SampleController', function($scope, $rootScope) {
  $scope.transferedValue = $rootScope.postEdit;
});
<!DOCTYPE html>
<html ng-app="app">

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
</head>
<body>
  <div ng-controller="TestController" ng-bind="postEdit"></div>
  <div ng-controller="SampleController" ng-bind="transferedValue"></div>
  </div>
</body>
</html>
developer033
  • 24,267
  • 8
  • 82
  • 108
-1

hai JohnDizzle ,

   You Can Pass the Data from One Controller to Anthor Controller Using BroadCast . And You can Store The LocalStorage And Retrive In Anthor Controll ALSO .. If Have Any Doughts Ask me.
Naveen Kumar
  • 50
  • 1
  • 8