you misunderstood the concept of $watch
, I'll explain:
First and foremost, AngularJS defines a concept of a so-called digest
cycle. This cycle can be considered as a loop, during which AngularJS
checks if there are any changes to all the variables watched by all
the $scopes. So if you have $scope.myVar defined in your controller
and this variable was marked for being watched, then you are
implicitly telling AngularJS to monitor the changes on myVar in each
iteration of the loop.
A natural follow-up question would be: Is everything attached to
$scope being watched? Fortunately, no. If you would watch for changes
to every object in your $scope, then quickly a digest loop would take
ages to evaluate and you would quickly run into performance issues.
That is why the AngularJS team gave us two ways of declaring some
$scope variable as being watched (read below).
$watch helps to listen for $scope changes
There are two ways of declaring a $scope variable as being watched
Meaning $watch won't tell you if the variable is empty but rather, if the variable changed.
for example:
unction MyController($scope) {
$scope.myVar = 1;
$scope.$watch('myVar', function() {
alert('hey, myVar has changed!');
});
$scope.buttonClicked = function() {
$scope.myVar = 2; // This will trigger $watch expression to kick in
};
}
if you want to check if the variable exists, create a function:
$scope.isNullOrEmptyOrUndefined = function (value) {
return !value;
}
and then check it like this (for example):
if($scope.isNullOrEmptyOrUndefined(product_files) {
//your logic
}