对于将 Timer 服务的时间值绑定到多个指令的最佳方法,我有点困惑。下面有两种方法,我不确定最佳实践是什么,或者其中一种方法是否具有性能优势。
在下面的代码中有 2 个计时器,第一个提供返回值,而第二个广播时间。控制器通过调用第一个工厂的方法来更新它的代码值,指令通过 $on 调用更新它们的值。
它们都工作得很好,但我相信一个比另一个有一些优势。
非常感谢任何输入。
'use strict';
var app = angular.module('ticker');
/**
* Timer that provides the current time when called directly
*/
app.factory('Timer', function($timeout) {
var _currentTime = 0;
var tick = function() {
$timeout(function() {
_currentTime += 1;
tick();
}, 2000);
};
tick(); // start the timer
return {
currentTime: function() { return _currentTime; }
};
});
/**
* Timer that broadcasts the current time
*/
app.factory('BroadcastTimer', function($timeout, $rootScope) {
var _currentTime = 0;
var tick = function() {
$timeout(function() {
_currentTime += 1;
$rootScope.$broadcast('tick', _currentTime);
tick();
}, 2000);
};
tick(); // start the timer
});
/**
* Handle the list of all the user's current stocks
*/
app.controller('StocksCtrl', function ($scope, Timer) {
/**
* List of all the user's current watched stocks
*/
$scope.watchedStocks = [
{ name: 'Google', symbol: 'GOOG', closings: [ 20, 23, 25, 24, 26, 30, 26, 30, 34, 40, 47, 50 ] },
{ name: 'Apple', symbol: 'AAPL', closings: [ 12, 15, 17, 13, 18, 21, 17, 24, 28, 33, 29, 34 ] },
];
/**
* Bind the current time to the Time factory
*/
$scope.currentTime = function() {
return Timer.currentTime();
};
});
/**
* Allows one to watch a stock and buy when the price is right.
*/
app.directive('watch', function(BroadcastTimer) {
return {
restrict: 'E',
templateUrl: 'watch.html',
scope: {
stock: '='
},
controller: function($scope) {
/**
* Listen to the BroadcastTimer's tick
*/
$scope.$on('tick', function(event, time) {
var timeIndex = time % $scope.stock.closings.length;
$scope.price = $scope.stock.closings[timeIndex];
});
}
}
});