我有一个使用Ionic的移动应用程序,它允许用户创建日志条目,并允许他们选择他们所在的时区。所选时区并不总是它们所在的当前时区。我正在使用角矩库来完成这个任务。
事情大多是可行的,但我需要根据用户选择的设置,让angularMomentConfig成为一个动态值。如果我硬编码时区,那么所有的东西都适用于那个时区。
.constant('angularMomentConfig', {
timezone: 'America/Buenos_Aires'
})但是,我需要使时区成为一个基于所选时区的动态值。我知道这个常量不能在角度应用程序中改变,所以使用它是不对的。只是我不知道该用什么,也不知道是否可能。我试过使用.value()而不是.constant(),但这在角矩中行不通。据我所见,没有办法将外部值注入一个常量,但也许还有其他方法来设置它,但我不知道。
目前,我有一个.run,它获取它们的设置并在本地存储它们,其中包括它们的时区:
.run(function(config, localStorageService, $http){
$http({
url: config.apiUrl + 'hos/settings/'
}).then(function(data) {
localStorageService.set('settings', data.data);
// their timezone is here
console.log(localStorageService.get('settings').timezone);
}, function(err) {
console.log(err);
});
}发布于 2016-02-02 13:00:59
除了设置angularMomentConfig常量之外,您还可以使用amMoment服务,并在任何时候调用它的changeTimezone()方法,如下所示:
.controller('mainController', function($scope, amMoment) {
amMoment.changeTimezone('America/Buenos_Aires');
});因此,例如,您可以在.run()函数中使用此方法。
下面是一个工作片段,它演示了这些方法和changeLocale:
angular.module('timeApp', ['angularMoment'])
.controller('mainController', function($scope, amMoment) {
var vm = this;
vm.time = new Date();
$scope.timezones = [{
id: 1,
name: 'America/Buenos_Aires',
locale: 'pt'
}, {
id: 2,
name: 'Europe/Paris',
locale: 'fr'
}, {
id: 3,
name: 'Australia/Melbourne',
locale: 'en'
}];
$scope.updateTz = function() {
console.log("$scope.timezone=", $scope.timezone)
amMoment.changeTimezone($scope.timezone.name);
amMoment.changeLocale($scope.timezone.locale);
}
// initial default values
$scope.timezone = $scope.timezones[0];
$scope.updateTz();
});<script src="//code.angularjs.org/1.4.8/angular.js"></script>
<script src="//momentjs.com/downloads/moment-with-locales.js"></script>
<script src="//momentjs.com/downloads/moment-timezone-with-data-2010-2020.js"></script>
<script src="//rawgit.com/urish/angular-moment/master/angular-moment.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootswatch/3.3.2/flatly/bootstrap.min.css">
<div class="container" ng-app="timeApp" ng-controller="mainController as main">
<div class="form-group">
<label>Time zones:</label>
<select class="form-control" ng-options="item as item.name+' ('+item.locale+')' for item in timezones track by item.id" ng-model="timezone" ng-change="updateTz()"></select>
</div>
<div class="well">
<h2>Date Format <small>(filter)</small></h2>
<time title="{{ main.time | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}">{{ main.time | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}</time>
</div>
<div class="well">
<h2>Calendar Format <small>(filter)</small></h2>
<time title="{{ main.time | amDateFormat: 'dddd, MMMM Do YYYY, h:mm a' }}">{{ main.time | amCalendar }}</time>
</div>
</div>
https://stackoverflow.com/questions/35067149
复制相似问题