2013-05-06 491 views
1

我創建一個使用角度計數器,這是我的第一遍。出於某種原因,當我更新timeRemaining值時,UI不會更新。我可以看到設置新值的那一行正在被命中並且新值確實不同,但它看起來好像並沒有更新$ scope值(或者至少綁定沒有被觸發)。任何想法我做錯了什麼?angularjs範圍值不更新

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> 

回答

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指令。