Dean Zaslow Dean Zaslow - 2 months ago 9
AngularJS Question

Angular - Directive with controllerAs, bindToController, and $scope.$watch

I have a fairly straightforward AngularJS question to which I cannot seem to find an answer:

How would I go about using

$scope.$watch()
in a directive controller while also using the
controllerAs
and
bindToController
options?

Please let me know if you need any clarification on what I mean exactly.

Answer

Well, $scope.$watch watches for expressions so assuming you're binding your controller to the name vm (e.g. controllerAs: 'vm') you should use

$scope.$watch('vm.somethingToWatch', function(newval, oldval) {...})

You will need to still inject the $scope though, since $watch is not available on controller instances by themselves.