I have this small sample in which I hoped to see log messages in browser console indicating $scope watcher is working well, but it's unfortunately not the case.
<!doctype html>
<html ng-app="demo">
<head>
<script src="bower_components/angular/angular.js"></script>
<script>
var app = angular.module('demo', ['ng']);
app.controller('demoCtrl', function($scope) {
var self = this;
self.searchText = '';
$scope.$watch('self.searchText', function(n, p) {
console.log('searchText changed from', n, 'to', p);
});
});
</script>
</head>
<body ng-controller="demoCtrl as ctrl">
<input type="text" ng-model="ctrl.searchText" />
</body>
</html>
Change your
$watch
to:In form you used
$scope.$watch
watching expression should be part of scope or root scope. So you should change your code like this:or use another form and change you code like this:
The answer is simple -
Angular watches the expression on the scope variable and not on the controller instance.
To make the code work you need to do modify the controller code as following
You need to use the alias
ctrl
(notself
) in$scope.$watch(...)
:When
ng-controller="demoCtrl as ctrl"
is used, Angular creates a link to the controller context objectthis
into the scope:$scope.ctrl
.