Yesterday, I realized that in my angularJS 1.4.8 application, the $scope.$watch doesn't trigger on every change causing a bug to occur.
Is there a way to make it work on every change immediately? For example, in this code snippet, I want the function in watch to be triggered upon every change in the message:
(function(){
angular.module('myApp', [])
.controller('myAppController', myAppController)
function myAppController($scope){
console.log('controller loading !');
$scope.message = 'message1';
$scope.$watch('message', function(newMessage){
console.log('newMessage', newMessage)
});
function changeMessage(){
$scope.message='hi';
$scope.message='hi12';
}
changeMessage();
}
})();
The console output will be:
controller loading !
newMessage hi22
Plunker link available: https://plnkr.co/edit/SA1AcIVwr04uIUQFixAO?p=preview
Edit: I am curious if there are any alternative methods besides wrapping the change with a timeout and using scope.apply. In my original code, there are multiple instances where I change the scope property and I would like to find a solution that does not require this for every change.