0
votes

I've got custom directive that add's a property to the scope in side the link function, then it add's a watch to it. If i changed the value of the scope property from the controller the watch gets fire. If i change that same value from inside the directive it won't get fired.

Here is an example: http://jsbin.com/bocixiha/3/edit

See the setTimeout inside the directive, this change doesn't have any affect.

p.s: This is only a simulation of what i have an i'm not using the setTimeout but it works the same way.

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

app.controller('myCtrl', function($scope) {
  $scope.changeProp = function() {
    $scope.options.someProperty = "Hello Stackoverflow";
  };
});

app.directive('mydir', function() {
  return {
    priority: 5001,
    restrict: 'A',
    compile: function(element, attrs) {
      return function(scope, element, attrs) {
        scope.options = {
          someProperty: "Hello World"
        };

        setTimeout(function() {
          console.log("Timeout Fired!");
          scope.options.someProperty = "This never gets set";
        }, 5000);

        scope.$watch('options.someProperty', function(n,o) {
          //This will fire when value changed from controller only.
          console.log("New: " + n + " Old: " + o);
        });
      };
    }
  };  
});
2

2 Answers

3
votes

Angular.js needs to be notified of the change. setTimeout by itself does not tell Angular to refresh the models; you need to either use the $timeout service instead of setTimeout or wrap the contents of your setTimeout callback in scope.$apply() in order to make Angular aware of the fact that something on the scope might have been changed.

2
votes

Replace setTimeout with $timeout.Wheneve model is changed, angular should be notified to update the view.By using $timeout function, that notification will be triggered automatically,otherwise you need to call $scope.$apply function.