angularjsangularjs-directiveangularjs-scopeangularjs-controllerangularjs-watch

Angular $watch not working on controller variable updated by directive


I am trying to place a watch on controller variable which gets updated from a directive using function mapping. variable is getting updated and logged in console but watch on it not working.

Code Snippet :

index.html

<body ng-app="myApp" ng-controller="myCtrl">
<div>
  <test on-click="update()"></test>
</div>

app.js

var myApp = angular.module('myApp', []);

myApp.controller('myCtrl', function($scope){

  $scope.test = {
    value: false
  };

  $scope.update = function() {
    $scope.test.value = !$scope.test.value;
    console.log("Update: " + $scope.test.value);
  };

  $scope.$watch('test', function(newVal){
    console.log("Watch: " + newVal.value);
  }, true);

});

myApp.directive('test', function($compile){
  return {
    restrict: 'E',
    transclude: true,
    replace: true,
    scope: {
      onClick: '&'
    },
        template: '<div ng-transclude=""></div>',
        link: function(scope, element, attrs) {
          var $buttonElem = $('<button>Test</button>').appendTo(element);

          $buttonElem.click(function(){
            scope.onClick();
          });
        }
  }
});

Plunker Link is : https://plnkr.co/edit/41WVLTNCE8GdoCdHHuFO?p=preview


Solution

  • The problem is that the directive is raising the event using code that is not apart of AngularJS instead of using an ng-click in its template. If you can't modify the directive, then wrap your event handler in $scope.$apply instead.

    $scope.update = function() {
        $scope.$apply(function(){
            $scope.test.value = !$scope.test.value;
            console.log("Update: " + $scope.test.value);
        });
    };