Angular指令回调不起作用

时间:2015-06-03 08:34:00

标签: angularjs angularjs-directive callback

我确定我犯了一个错误,但我找不到它。 HTML:

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

这是javascript代码:

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);
    }
  };
}]);

我无法找到我做错的事情,我开发了另一个带回调的指令,而且这些指令运行良好。

此处代码为:http://codepen.io/madridserginho/pen/JdWNEK

2 个答案:

答案 0 :(得分:1)

@Arek说的话......

也可以使用:callback: '=timeoutCallback'

而不是callback: '&timeoutCallback'

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

答案 1 :(得分:0)

<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属性(如timeoutCallback)在视图中被转换为dash case(如timeout-callback),这就是绑定不起作用的原因。