タイマー サービスの時間値を多くのディレクティブにバインドする最善の方法について、少し混乱しています。以下に 2 つの方法を示しますが、何がベスト プラクティスなのか、またはどちらか一方にパフォーマンス上の利点があるかどうかはわかりません。
以下のコードには 2 つのタイマーがあり、最初のタイマーは戻り値を提供し、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];
});
}
}
});