Search code examples
javascriptangularjsangularjs-directiveangularjs-scopeangularjs-watch

scope.$watch not firing on variable change


I have the following snippet of code below. The problem I'm having is that whenever the value of modal.isOpen is set to true, the $watch statement does not fire. I'm trying to avoid using scope.$apply. What am I doing wrong here...

Inside Link function in an Angular directive:

              link: function (scope, elem, attrs) {

              scope.$watch('modal.isOpen', function(newValue, oldValue) {
                  if (newValue)
                      console.log("This does not trigger...");
              }, true);

              $document.bind('keydown', function (e) {

                  if(e.keyCode >= 48 && e.keyCode <= 90) {
                      scope.modal.isOpen = true;
                      elem.find('input')[0].focus();

                  }
              ..........
              });

Solution

  • You should keep watch on property which shouldn't have scope in the string given to $watch function.

    scope.$watch('modal.isOpen', function(newValue, oldValue) {
    

    And the while modifying scope from custom event, wouldn't update binding. You need to kick digest cycle using $timeout/$apply() to update binding.(If any code ran ouside of angular context, angular doesn't run digest cycle to update bindings).

    $document.bind('keydown', function(e) {
    
      if (e.keyCode >= 48 && e.keyCode <= 90) {
        $timeout(function() {
          scope.modal.isOpen = true;
          elem.find('input')[0].focus();
        });
      }
      ..........
    });