user3501613
user3501613

Reputation: 610

Unable to access scope variable inside $watch

I am developing one filter in angularJS. Everything is working fine but only in one place I am unable to access the scope object but when I change the code it is working fine but I want to know what is the problem.I think my understanding is wrong about scope and directives.

inside one directive I am accessing one array and in scope.watch function I try to access that array but it is not working

working code

var currentScope=scope.mainList[scope.$index].list;
//this will hit whenever any of the scope variable changes
scope.$watch(function () {
  var hasTrue, hasFalse;
  angular.forEach(currentScope, function (v) {
    if (v["isSelected"]) {
      hasTrue = true;
    } else {
      hasFalse = true;
    }
  });
  if (hasTrue && hasFalse) {
    iElement.attr('checked', false);
   // iElement.addClass('greyed');
  } else {
    iElement.attr('checked', hasTrue);
   // iElement.removeClass('greyed');
  }
}, true);

this is not working

var currentScope=scope.mainList[scope.$index].list;
 //this will hit only when this corresponding scope variable changes
scope.$watch(currentScope,function (newVal) {
  var hasTrue, hasFalse;
  angular.forEach(newVal, function (v) {
    if (v["isSelected"]) {
      hasTrue = true;
    } else {
      hasFalse = true;
    }
  });
  if (hasTrue && hasFalse) {
    iElement.attr('checked', false);
   // iElement.addClass('greyed');
  } else {
    iElement.attr('checked', hasTrue);
   // iElement.removeClass('greyed');
  }
}, true);

I need this second code but whenever I changes any of the variables it is not hitting and its coming undefined

please check this bellow link it will give more idea.....

Code

Upvotes: 1

Views: 1053

Answers (1)

2ps
2ps

Reputation: 15916

Expanding on @tobi’s comment, here is the recommended way to have written your watch function:

var currentScope=scope.mainList[scope.$index].list;
scope.$watch(function () { return currentScope; }, function (newVal) {
  var hasTrue = false, hasFalse = false;
  angular.forEach(newVal, function (v) {
    if (v["isSelected"]) {
      hasTrue = true;
    } else {
      hasFalse = true;
    }
  });
  if (hasTrue && hasFalse) {
    iElement.attr('checked', false);
   // iElement.addClass('greyed');
  } else {
    iElement.attr('checked', hasTrue);
   // iElement.removeClass('greyed');
  }
});

Alternatively, you can do this:

scope.currentScope=scope.mainList[scope.$index].list;
scope.$watch('currentScope', function (newVal) {
  var hasTrue = false, hasFalse = false;
  angular.forEach(newVal, function (v) {
    if (v["isSelected"]) {
      hasTrue = true;
    } else {
      hasFalse = true;
    }
  });
  if (hasTrue && hasFalse) {
    iElement.attr('checked', false);
   // iElement.addClass('greyed');
  } else {
    iElement.attr('checked', hasTrue);
   // iElement.removeClass('greyed');
  }
});

Upvotes: 1

Related Questions