naCheex naCheex - 3 months ago 27
AngularJS Question

angularjs $watch is not working in directive

Trying to load data in directive by using one-way binding here is the code.

<nav-directive depts="dummyData"></nav-directive>

APP.directive('navDirective', navDirective);


here is directive

function navDirective($state, navigationService,$rootScope) {

return {
restrict: "E",
scope: { depts: '=' },
templateUrl: '/app/shared/common-directives/navigation/navigation.view.html',
link: function(scope, elem, attr) {
$rootScope.$watch('depts', function(newVal, oldVal) {
// or $watchCollection if students is an array
if (newVal) {
console.log('in Dir');
console.log(scope.depts)
}
},true);


}
};
}


scope.depts is undefined when data updated by conroller.

Answer

The syntax $scope.$watch('someString') tells Angular to watch the value of the variable named someString in the given $scope. Here you use it on the $rootScope, so it will look for a variable depts defined on the rootScope, and it won't find one because depts is only defined on scope.

So just use scope.$watch('depts').