Today marks my first attempt at utilizing Angular's watch function, but I'm having trouble getting it to function properly. Within my codebase, there exists a service named apiService
, housing a variable called myFile
. By injecting this service into my controller, I aim to monitor any changes in the value of apiService.myFile
. Regrettably, it seems that the watch function only triggers upon initial webpage load and fails to react when the apiService.myFile
variable undergoes a change. Below is the snippet showcasing the watch implementation:
$scope.$watch(function(){return apiService.myFile}, function (newVal, oldVal, scope) {
console.log("service changed: "+newVal +" : "+oldVal+" : "+ scope);
});
Could you shed some light on why it isn't responding to changes in myFile
?
UPDATE 1:
Here's how I update the value of apiService.myFile
within the service:
ApiService.prototype.uploadFile = function(fileContent) {
$.ajax({
url: "/space_uploadFile/",
type: "POST",
dataType: "json",
data: {
fileContent: fileContent
},
contentType: "application/json",
cache: false,
timeout: 5000,
complete: function() {
//called when complete
console.log('process complete');
},
success: function(data) {
this.myFile =data;
console.log("this.myFile: "+this.myFile);
console.log('process success');
},
error: function() {
console.log('process error');
},
});
};