0

I'm trying to figure out why directive's controller doesn't update data

angular.module('sample', [])
.directive('countdown', function () {

function CountdownController() {
    var countdownController = this;

    countdownController.digit = 5;

    setTimeout(function () {
        console.log('fired');
        countdownController.digit = 200;
    }, 3000);

}


return {
    restrict: 'E',
    controller: CountdownController,
    controllerAs: 'countdownController',
    bindToController: true,
    template: '{{countdownController.digit}}'
}
});

https://jsfiddle.net/mghs52my/

I know I can use $scope.$apply() to force changes, but why should I do that?

  • 1
    Maybe using the $timeout service from Angular helps (not using setTimeout - which is plain JS). Therefore you wouldn't need to call $scope.$apply(). – ilmgb Aug 08 '15 at 10:53

2 Answers2

1

setTimeout() is outside of any of angular's core services or directives. Whenever you change scope from outside of the core you need to use $apply().

For this reason angular has $timeout which is a wrapper for setTimout() and will call $apply() internally

Change to:

angular.module('sample', [])
    .directive('countdown', function ($timeout) {

    function CountdownController() {
        var countdownController = this;

        countdownController.digit = 5;

        $timeout(function () {
            console.log('fired');
            countdownController.digit = 200;
        }, 3000);

    }


    return {
        restrict: 'E',
        controller: CountdownController,
        controllerAs: 'countdownController',
        bindToController: true,
        template: '{{countdownController.digit}}'
    }
});

DEMO

charlietfl
  • 170,828
  • 13
  • 121
  • 150
0

If you want to change you model in each time after some time interval

use $interval instead of setTimeout()

angular.module('sample', [])
    .directive('countdown', function () {

    function CountdownController($interval) {
        var countdownController = this;

        countdownController.digit = 5;

        $interval(function () {
            console.log('fired');
            countdownController.digit = 200;
        }, 3000);

    }


    return {
        restrict: 'E',
        controller: CountdownController,
        controllerAs: 'countdownController',
        bindToController: true,
        template: '{{countdownController.digit}}'
    }
});

'setInterval' vs 'setTimeout' and setTimeout or setInterval

$timeout vs $interval

Community
  • 1
  • 1
gaurav bhavsar
  • 2,033
  • 2
  • 22
  • 36