Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update .value inside controller angularjs?

I tried to pass value form one module to another module in angularjs. using .value which is working fine.

working:-

var app = angular.module('app', []);
app.value('movieTitle', 'The Matrix');
var app1 =angular.module('app1', ['app']);
app1.controller('MyController', function (movieTitle) {
//Here I am getting value. which is working fine.
console.log(movieTitle)
})

Not working:-

var app = angular.module('app', []);
app.value('movieTitle', 'The Matrix');
app.controller('MyController', function (movieTitle) {
//Here I override the value.
movieTitle = "The Matrix Reloaded";
})
var app1 =angular.module('app1', ['app']);
app1.controller('MyController', function (movieTitle) {
//Here I am getting old value not update value.
console.log(movieTitle)
})

In Second sample I tried to update the value its updating fine. but while Am access the value from other module that time it shows only old value not updated one can anyone help me this. where i did mistake...

like image 994
Suresh B Avatar asked Nov 09 '22 17:11

Suresh B


1 Answers

JavaScript strings are immutable, so you cannot update the injected value (as it's a string) - you're just changing the content of the injected variable. You could take another approach at containing the string within an object, now you can update the string in the object:

var movie = { title: 'The Matrix' };

angular.module('app', [])
    .value('movie', movie)
    .controller('MyController', function (movie) {
        //Here I override the value.
        movie.title = "The Matrix Reloaded";
    });

angular.module('app1', ['app'])
    .controller('MyController', function (movie) {
        console.log(movie.title);
    });
like image 69
Matthew Mcveigh Avatar answered Nov 15 '22 05:11

Matthew Mcveigh