naCheex naCheex - 1 year ago 126
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');


scope.depts is undefined when data updated by conroller.

Answer Source

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').

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download