I am trying to have angular watch the $viewValue of a controller from inside a directive.
fiddle: http://jsfiddle.net/dkrotts/TfTr5/5/
function foo($scope, $timeout) {
$scope.bar = "Lorem ipsum";
$timeout(function() {
$scope.bar = "Dolor sit amet";
}, 2000);
}
myApp.directive('myDirective', function() {
return {
restrict: 'A',
require: '?ngModel',
link: function (scope, element, attrs, controller) {
scope.$watch(controller.$viewValue, function() {
console.log("Changed to " + controller.$viewValue);
});
}
}
});
As is, the $watch function is not catching the model change done after 2 seconds from inside the controller. What am I missing?
$watchaccepts the “name” of the property to watch in the scope, you’re asking it to watch the value. Change it to watchattrs.ngModelwhich returns “bar”, now you’re watchingscope.bar. You can get the value the same way you were or usescope[attrs.ngModel]which is like sayingscope["bar"]which again, is the same asscope.bar.To clarify user271996’s comment:
scope.$evalis used because you may pass object notation into theng-modelattribute. i.e.ng-model="someObj.someProperty"which won’t work becausescope["someObj.someProperty"]is not valid.scope.$evalis used to evaluate that string into an actual object so thatscope["someObj.someProperty"]becomesscope.someObj.someProperty.