use*_*123 21 javascript javascript-framework angularjs
我正在尝试在angularjs文档中给出的代码(在这里给出:http://jsfiddle.net/zGqB8/)它只实现了一个时间工厂并使用$ timeout来更新每秒后的时间对象.
angular.module('timeApp', [])
.factory('time', function($timeout) {
var time = {};
(function tick () {
time.now = new Date().toString();
$timeout(tick, 1000); // how to do it using setInterval() ?
})();
return time;
});
Run Code Online (Sandbox Code Playgroud)
如何使用setInterval()函数而不是$ timeout()来完成它?我知道需要使用scope.$apply()进入角度执行上下文但是如何在工厂函数中工作?我的意思是,在控制器中,我们有一个范围,但我们没有工厂功能的范围?
asg*_*oth 38
您可以将其$timeout用作间隔.
var myIntervalFunction = function() {
cancelRefresh = $timeout(function myFunction() {
// do something
cancelRefresh = $timeout(myIntervalFunction, 60000);
},60000);
};
Run Code Online (Sandbox Code Playgroud)
如果视图被破坏,你可以通过监听来销毁它$destroy:
$scope.$on('$destroy', function(e) {
$timeout.cancel(cancelRefresh);
});
Run Code Online (Sandbox Code Playgroud)
Bra*_*ens 32
更新
Angular在版本1.2中实现了$ interval功能 - http://docs.angularjs.org/api/ng.$interval
下面的遗留示例,除非您使用的是早于1.2的版本,否则请忽略它.
Angular中的setInterval实现 -
我创建了一个名为timeFunctions的工厂,它公开了$ setInterval和$ clearInterval.
请注意,任何时候我需要修改工厂中的范围我已经通过了.我不确定这是否符合"Angular方式"的做法,但它运作良好.
app.factory('timeFunctions', [
"$timeout",
function timeFunctions($timeout) {
var _intervals = {}, _intervalUID = 1;
return {
$setInterval: function(operation, interval, $scope) {
var _internalId = _intervalUID++;
_intervals[ _internalId ] = $timeout(function intervalOperation(){
operation( $scope || undefined );
_intervals[ _internalId ] = $timeout(intervalOperation, interval);
}, interval);
return _internalId;
},
$clearInterval: function(id) {
return $timeout.cancel( _intervals[ id ] );
}
}
}
]);
Run Code Online (Sandbox Code Playgroud)
用法示例:
app.controller('myController', [
'$scope', 'timeFunctions',
function myController($scope, timeFunctions) {
$scope.startFeature = function() {
// scrollTimeout will store the unique ID for the $setInterval instance
return $scope.scrollTimeout = timeFunctions.$setInterval(scroll, 5000, $scope);
// Function called on interval with scope available
function scroll($scope) {
console.log('scroll', $scope);
$scope.currentPage++;
}
},
$scope.stopFeature = function() {
return timeFunctions.$clearInterval( $scope.scrollTimeout );
}
}
]);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
39050 次 |
| 最近记录: |