angularjs范围值未更新

时间:2013-05-06 00:31:08

标签: javascript angularjs

我正在创建一个使用角度的计数器,这是我的第一个传球。出于某种原因,当我更新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>

1 个答案:

答案 0 :(得分: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指令。