I am currently working with a service called sharedData
and a controller named HostController
. My goal is to have the HostController
monitor the saveDataObj
variable within the sharedData
service, and then update the value of host.dataOut
, which will be reflected in the view as an ngModel attribute.
The challenge I'm facing is that I am unsure about how to effectively use the $watch
function. Ideally, I want the value of host.dataOut
to be automatically updated whenever there is a change in the saveDataObj
variable in the sharedData
service (or whenever the setData
method is called).
Upon running the following code snippet, I receive the following message in the console:
sharedData.getData(): Object { }
This output is expected during initialization. However, when I trigger the
setData
method from another controller to modify the value of saveDataObj
, no new logs are displayed in the console.
Can someone please point out what mistake I might be making?
angular.module('app', [])
.factory('sharedData',function(){
var saveDataObj = {};
return {
getData: function(){
return saveDataObj;
},
setData: function(data){
saveDataObj = data;
}
};
})
.controller('HostController',['$scope','sharedData',function($scope,sharedData){
$scope.sharedData = sharedData;
var host = this;
host.dataOut = {};
$scope.$watch(
'sharedData.getData()',
function handleDataChange(newValue,oldValue) {
console.log("sharedData.getData():",newValue);
host.dataOut = newValue;
}
);
}])