【问题标题】:Angular directive callback isn't workingAngular 指令回调不起作用
【发布时间】:2015-06-03 08:33:59
【问题描述】:

我确定我犯了一个错误,但我找不到它。 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

【问题讨论】:

    标签: angularjs angularjs-directive callback


    【解决方案1】:

    @Arek 说了什么...

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

    而不是callback: '&amp;timeoutCallback'

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

    【讨论】:

    • 很好,我没有注意到&amp;,这给以这种方式绑定的调用函数带来了不必要的复杂性。
    【解决方案2】:
    <html ng-app="countdown">
      <body>
        <div class="container" ng-controller="cc">
          {{status}}<br>
          <countdown duration="3" timeout-callback="cbck"></countdown>
        </div>
      </body>
    </html>
    

    指令中的驼峰式大小写属性(如timeoutCallback)在视图中被转换为破折号大小写(如timeout-callback),这就是绑定不起作用的原因。

    【讨论】:

      猜你喜欢
      • 2018-12-17
      • 1970-01-01
      • 2018-11-09
      • 2018-04-12
      • 2023-03-27
      • 1970-01-01
      • 2016-09-14
      • 2017-02-18
      • 1970-01-01
      相关资源
      最近更新 更多