After creating a controller and directive with local scope, I added a watcher on a scope variable in the postLink method and implemented $interval to change the variable. Additionally, I included a watcher on the binded variable in the controller.
console.clear();
var myApp = angular.module('myApp', []);
myApp.controller('MainCtrl', ['$scope',
function($scope) {
$scope.$watch(function() {
return $scope.ctrlVar;
}, function(newValue) {
console.log('WATCHER TWO: newValue = ', newValue);
}, true);
}
]);
myApp.directive('testDirective',
['$interval', function($interval) {
return {
scope: {
date: '=dateModel'
},
template: "<input type='text' value='{{date}}' />",
restrict: 'E',
link: function postLink(scope, element) {
console.log('link');
var i = 1;
$interval(function() {
scope.date = i++;
}, 1000);
scope.$watch('date', function(){
console.log('WATCHER ONE: newValue = ', scope.date);
});
}
};
}]
);
html:
<body ng-app="myApp">
<div ng-controller="MainCtrl">
<test-directive date-model="ctrlVar"></test-directive>
</div>
<script src="script.js"></script>
</body>
</html>
The order of invoking watch listeners is as follows:
WATCHER IN CONTROLLER: newValue = undefined
script.js:32 WATCHER IN DIRECTIVE: newValue = undefined
script.js:32 WATCHER IN DIRECTIVE: newValue = 1
script.js:10 WATCHER IN CONTROLLER: newValue = 1
script.js:32 WATCHER IN DIRECTIVE: newValue = 2
script.js:10 WATCHER IN CONTROLLER: newValue = 2
In some cases, the behavior of the watchers can be different, especially when dealing with more complex production code. Have you experienced this issue before?
If you want to manage the order of watch listeners, check out this example http://plnkr.co/edit/QzeZar?p=preview