Lee
Lee

Reputation: 791

angularjs interval applies changes in rootscope

I followed angularjs's example to doing a timer that updates every second.

.directive('myCurrentTime', ['$interval', 'dateFilter', function($interval, dateFilter) {

  return function(scope, element, attrs) {
    var stopTime;

    function updateTime() {
      element.text(dateFilter(new Date(), "hh:mm:ss"));
    }

    updateTime();

    stopTime = $interval(updateTime, 1000);

    element.on('$destroy', function() {
      $interval.cancel(stopTime);
    });
  }
}]);

My problem is that on every call to function of the interval(updateTime), the whole scope is updated instead of only the scope of the directive. The problem is that I have filters for languages in the root scope and then it calls all the filters every time which is pretty bad..

Is it possible to only apply the function on the local scope of the directive? I tryed using:

 function updateTime() {

     scope.$apply(function () {
           element.text(dateFilter(new Date(), "hh:mm:ss"));
     });
 }

 stopTime = $interval(updateTime, 1000, null, false);

but with no success.

I added a fiddle with the example: http://jsfiddle.net/f1qqw4d9/2/

I don't want the message below the time to change

Thanks

Upvotes: 0

Views: 1461

Answers (1)

Julian Hollmann
Julian Hollmann

Reputation: 2912

Yes, it's possible. Create your interval either with window.setInterval or window.setTimeoutand call scope.$digest after each cycle.

If you're interested in this topic in general you can read this very interesting article: https://coderwall.com/p/d_aisq

Edit: Please see my example on jsfiddle: http://jsfiddle.net/huxhpy0L/2/

One thing that was kind of confusing is, that you're directly modifying the DOM. In that case you don't need any apply. The content will change either way.

Upvotes: 3

Related Questions