1

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

3
  • Try calling scope.$apply() in the link function. Commented May 9, 2016 at 14:13
  • Can't do it. Consider directive as a third party library which can not be updated. Commented May 9, 2016 at 14:15
  • @Prateek but you can do a $timeout(function() { $scope.$apply(); }); inside your controller update function which would do the same thing (even if it is ugly) Commented May 9, 2016 at 14:22

1 Answer 1

2

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);
    });
};
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.