I have a problem where I have a service which exposes a string. There is a function on this service which updates the value of the string. The service internally knows that the value has changed, however, externally the value NEVER updates.
If I nest the string inside an object then it all works, but I don't really want to nest it.
Can anyone explain why this is happening? It feels like it should work and feels like I am missing something basic.
Service:
myApp.service('neverChanges', function () {
var id = 'Hello';
var changeId = function () {
console.log('pre change:' + id);
id = 'World';
console.log('post change:' + id);
};
return {
id: id,
changeId: changeId
};
});
Controller:
myApp.controller('Controller1', ['neverChanges', function (neverChanges) {
this.idValue = function() {
return neverChanges.id;
}
this.clickHandler = function () {
console.log('Trust me, I did fire...');
neverChanges.changeId();
console.log('external post change:' + neverChanges.id);
};
}]);
Markup:
<div ng-app="myApp">
<div ng-controller="Controller1 as vm">
<h3>This will never change:</h3>
<button ng-click="vm.clickHandler()">Click Me!</button>
<p>Values:</p>
<p>id: {{vm.idValue()}}</p>
</div>
Fiddle showing the two scenarios: http://jsfiddle.net/KyleMuir/2nhoc2rz/