troyz
troyz

Reputation: 1385

Modify a global value from a controller AngularJS

i'm trying to modify a global value from a controller and use it, modified , on another one but the variable holds the old value.

app.js

var app = angular.module('PressRoom', []);
app.value('globals',
    {
        companyName: 'My company',
        appName: 'My app',
        user: {
            name: 'Test user',
            img: '',
            role: ''
        }
    });

Controller where i want to modify it

app.controller('LoginController', ['$scope','globals',function($scope,globals)
{
    $scope.globals = globals;
    globals.user.name = "Brand new user";
    // Redirect to dashboard.
}]);

Controller where i want to use it modified.

app.controller('DashboardController', ['$scope','globals',function($scope,globals,)
{
    $scope.globals = globals;
}]);

In the view of the last controller, i'm using the globals values on a directive, but it displays Test user instead of Brand new user

Upvotes: 0

Views: 162

Answers (2)

dlock
dlock

Reputation: 9577

You can't. But you can create a Service that has a getter and a setter and use it the same way you would use a value. Needless to say, you can even take this to be a bit smarter and create a Service that you can use as a key,value store. For example, MyDataStore.set("myVal",1) and MyDataStore.get("myVal") But for the sake of simplicity, Here is a simple Service demonstrating my suggested approach.

angular.module("my", [])
  .service("MyValue", function() {
    return {
      set: function(val) {
        this.val = val;
      },
      get: function() {
        return this.val;
      }
    }
  })
  .run(function(MyValue) {
    MyValue.set("Initial Value");
  })
  .controller("MyController", function(MyValue) {
    console.log(MyValue.get()); //prints Initial Value
    MyValue.set("New Value");
    console.log(MyValue.get()); //prints New Value
  })

https://jsfiddle.net/oL0m2f7j/1/

Upvotes: 1

Vinay
Vinay

Reputation: 558

Use $rootScope variable and declare it inside of your factory/service (Not in controller)

So that you can use it through out your application and you can copy that value to local scope or override it if needed.

app.factory('MyFactory', MyFactory);

function MyFactory() {
    $rootScope.userName = '';
}
app.controller('MyController', MyController);

function MyController() {
    $scope.desiredName = $rootScope.userName;
    $scope.desiredName = 'Your desired value';
}

Upvotes: 0

Related Questions