DarthJS DarthJS - 5 months ago 18
Javascript Question

Angular watch doesn't work with controllerAs syntax

Have a problem with watching response.

I have a SettingsCtrl as settings and this is my view:



<input type="text" class="form-control" ng-model="settings.test.one" />
<input type="text" class="form-control" ng-model="settings.test.second" />





And this is my Controller:



app.controller('SettingsCtrl', function ($scope, settingsFactory, Test) {

var vm = this;


settingsFactory.test().then(function(response){

vm.test = response;
})

///// OR

vm.test = Test; // this is from ui-router resolve


$scope.$watch(angular.bind('vm', function () {
return vm.test;
}), function (newV, oldV) {
console.log(newV, oldV);
});

$scope.$watch(function watch(scope){
return vm.test;
}), function handle(newV, oldV) {
console.log(newV, oldV);
});

$scope.$watch('vm', function (newVal, oldVal) {
console.log('newVal, oldVal', newVal, oldVal);
});

});





I've been searching and have found different solutions, but non of them works.

**** It's watch only first time, when controller is loaded and I see my console logs, but when I try to make changes watchers do nothing.

What I'm doing wrong?

Answer

If I'm not wrong, your $watch is hit the first time a controller is loaded, but not when you change something in the object. If that's true, then try this:

$scope.$watch('vm', function (newVal, oldVal) {
    console.log('newVal, oldVal', newVal, oldVal);
}, true);

By default, $watch function watches the reference so if you only change a property of the watched object it will not be fired. By adding true at the end, you start deep watching, and you will get a hit each time you change a property of the object.

Comments