1

我正在使用 angular 创建一个计数器,这是我的第一遍。出于某种原因,当我更新timeRemaining值时,UI 不会更新。我可以看到设置新值的行被击中并且新值确实不同,但似乎 $scope 值没有被更新(或者至少绑定没有被触发)。任何想法我做错了什么?

var everydayModule = angular.module('Everyday', [])
  .factory('animate', function ($window, $rootScope) {
    var requestAnimationFrame = $window.requestAnimationFrame ||
      $window.mozRequestAnimationFrame ||
      $window.msRequestAnimationFrame ||
      $window.webkitRequestAnimationFrame;


    return function (frame) {
      requestAnimationFrame(function () {
        $rootScope.$apply(frame);
      });
    };
});

function countdown(timeRemaining, endDate, animate) {
  (function frame() {
    var now = new Date();
    var oneDay = 24 * 60 * 60 * 1000;
    timeRemaining = Math.abs((endDate.getTime() - now.getTime()) / oneDay);
    animate(frame);
  })();
}

function EverydayController($scope, animate) {
  $scope.timeRemaining = 0;
  $scope.endDate = new Date(2013, 06, 10);

  countdown($scope.timeRemaining, $scope.endDate, animate);
};

这是我的 HTML:

<html ng-app="Everyday">
<body>
    <div ng-controller="EverydayController">
        <div class="time" id="seconds">{{timeRemaining}}</div>
    </div>
4

1 回答 1

3

您不需要为此使用服务。

这是工作代码:

var timeRemaining = 0;
var endDate = new Date(2013, 06, 10);
var oneDay = 24 * 60 * 60 * 1000;

function EverydayController($scope) {
  $scope.timeRemaining = timeRemaining;
};
var requestAnimationFrame = window.requestAnimationFrame ||
    window.mozRequestAnimationFrame ||
    window.msRequestAnimationFrame ||
    window.webkitRequestAnimationFrame;

var loop = function () {
    updateModel('seconds', function(scope){
        var now = new Date();
        scope.timeRemaining = Math.abs((endDate.getTime() - now.getTime()) / oneDay);
        requestAnimationFrame(loop);
    });
}

requestAnimationFrame(loop);

function updateModel(element_id, callback){
    var sc = angular.element(document.getElementById(element_id)).scope();
    sc.$apply(function(sc){
        callback(sc);
    });
}

而且,这是一个工作小提琴:http: //jsfiddle.net/bHh5M/1/

此外,您不应该在控制器中做太多事情:http: //docs.angularjs.org/guide/dev_guide.mvc.understanding_controller - 请参阅“正确使用控制器”部分。

你可能想看看新的 ngAnimate 指令。

于 2013-05-06T01:58:26.673 回答