I am new to Angular, but i do not understand why controller updates data from service only in some cases ... http://plnkr.co/edit/pV8m11Bc1vItDSmQKECS?p=preview object1 and 2 are correctly updated, but objet3 is not. Seems that Service.get3() is just fired once. I understand that Angular watch for object changes, fine for object1 and object2 (that is a reference to object1) by the way, it's great. But it's not working with object3 ... ok it's not a reference... The question is : how to build new objects in service ?
Thank you, Philippe
var app = angular.module('App', []);
app.factory('Service', [
function() {
var object1 = ["TOTO"];
return {
get1: function() {
return object1;
},
get2: function() {
var object2 = object1;
return object2;
},
get3: function() {
var object3 = [];
/*
object1.forEach(function(entry) {
object3.push(entry);
console.log(entry);
});
*/
for (i = 0; i < object1.length; i++) {
object3.push(object1[i]);
}
return object3;
},
set: function(newValue) {
object1.push(newValue);
}
}
}
]);
app.controller('Controller', ['$rootScope', '$scope', 'Service',
function($rootScope, $scope, Service) {
$scope.object1 = Service.get1();
$scope.object2 = Service.get2();
$scope.object3 = Service.get3();
$scope.set = function() {
Service.set("TITI");
}
}
]);