Serginho
Serginho

Reputation: 7490

Angular directive callback isn't working

I'm sure I'm making a mistake but I can't find it. Html:

<html ng-app="countdown">
  <body>
    <div class="container" ng-controller="cc">
      {{status}}<br>
      <countdown duration="3" timeoutCallback="cbck"></countdown>
    </div>
  </body>
</html>

That's the javascript code:

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

app.controller('cc', function ($scope){
  $scope.status = 'countdown started ';
  $scope.cbck = function () {
    $scope.status = 'countdown finished';
  }
});
app.directive('countdown', ['$interval', function ($interval) {
  return {
    scope: {
      timer: '=duration',
      callback: '&timeoutCallback'
    },
    restrict: 'E',
    template: '<span>{{minutes}}:{{seconds}}</span>',
    link: function (scope, element, attrs){

      scope.ipromise = $interval(function() {
        var minutes, seconds;
        minutes = parseInt(scope.timer / 60, 10)
        seconds = parseInt(scope.timer % 60, 10);
        scope.minutes = minutes < 10 ? "0" + minutes : minutes;
        scope.seconds = seconds < 10 ? "0" + seconds : seconds;
        if(scope.timer > 0){
             scope.timer--;   
        }else{
          scope.callback();
          $interval.cancel(scope.ipromise);
        }
      }, 1000);
    }
  };
}]);

I can't find what I'm doing wrong, I developed another directives with callbacks and those work well.

Here the code: http://codepen.io/madridserginho/pen/JdWNEK

Upvotes: 0

Views: 463

Answers (2)

paul
paul

Reputation: 22001

What @Arek said...

also use: callback: '=timeoutCallback'

rather than callback: '&timeoutCallback'

http://codepen.io/anon/pen/PqpmgX

Upvotes: 1

rzelek
rzelek

Reputation: 4013

<html ng-app="countdown">
  <body>
    <div class="container" ng-controller="cc">
      {{status}}<br>
      <countdown duration="3" timeout-callback="cbck"></countdown>
    </div>
  </body>
</html>

Camel case attributes from directives (like timeoutCallback) are translated to dash case in view (like timeout-callback), that is why binding does not work.

Upvotes: 0

Related Questions