Reputation: 168
I am passing data from a controller, into a directive. The controller is changing the data, however I can not get the directive to respond when the data in the controller changes. Here is a link to JSFiddle: http://jsfiddle.net/mcardleliam/ReJQq/1/.
My html looks like this:
<div ng-app="app" ng-controller="appCtrl">
<h1 foo>Prop: {{prop}}</h1>
</div>
angular.module('app', [])
.controller('appCtrl', function($scope, $timeout) {
$scope.prop = 0;
var f = function() {
$scope.prop = $scope.prop += 1;
$timeout(f, 1000);
}
f();
})
.directive('foo', function() {
return {
restrict: 'A',
link: function(scope) {
console.log('initial prop', scope.prop);
scope.$watch(scope.prop, function() {
console.log("prop changed");
});
}
};
});
The "console.log("prop changed");" should be called every time the controllers $scope.prop property changes, but it is not. Anyone know what I am doing wrong?
Upvotes: 0
Views: 207
Reputation: 50245
You need this in directive:
scope.$watch('prop', function() {
console.log("prop changed");
});
Refer to the property as 'prop' instead of scope.prop
.
Upvotes: 1