使用 CoffeeScript 在 AngularJS 控制器上定义 $interval

Define $interval on a AngularJS controller with CoffeeScript

在 CoffeeScript 和 AngularJS 方面,我完全是个新手,现在我正忙于同时学习这两者。

我有一个 AngularJS 控制器,它发出一个 $http 请求来读取一个值。此 CoffeeScript 工作正常:

angular.module('app.controllers', []).controller('SalesTodayCtrl', [
        '$scope','$http'
        ($scope, $http) ->
        $http.get('http://myserver/sales/today/count').success (data) ->
            $scope.salesToday = data ])

现在我需要这个控制器每分钟刷新一次。谁能为我提供一个具体的代码示例来说明如何做到这一点?使用尽可能少的伪代码。

非常感谢帮助!

只是一个伪代码。我没有测试它,但确定它应该可以工作

countUp = ->
  $http.get('http://myserver/sales/today/count').success (data) ->
    $scope.salesToday = data
  return

$timeout countUp, 500

首先,我会在你的控制器上定义一个更新方法:

$scope.url = 'http://myserver/sales/today/count'

$scope.success = (data) ->
  $scope.salesToday = data

$scope.update = () ->
  $http.get($scope.url).success $scope.success

然后创建一个服务来处理'every minute'位。您可以使用 Angular 提供的 $interval 服务。

app.service 'Refresh', ($interval) ->
  @every = (update, ms) ->
    $interval update, ms

最后,将 Refresh 服务注入控制器并使用您的更新功能调用它。

app.controller 'SalesTodayCtrl', ($scope, $http, Refresh) ->
  # ... the other code
  Refresh.every $scope.update, 60000

这使用 setInterval 作为底层机制,但因为它是通过 Angular 的间隔包装器使用的,所以您无需担心手动触发摘要。

如果您需要以正好 1 分钟的间隔进行刷新,那么您可能会 运行 改为 setInterval issues. You probably want to look into doing delta time using requestAnimationFrame