我有一项控制用户常规设置的服务。
其中一个设置是日期的全球时间格式。 例如 - 如果用户选择了美国格式,则呈现给用户的所有时间都应采用AM PM格式,否则将呈现24小时时间。
* *设置全局用户设置 * /
app.factory('UserSettings', ['localStorageService', function (localStorageService) {
var UserSettings = {};
/**
* The user settings
* @type {}
*/
var userSettings = null;
/**
* The user settings key for the local storage
* @type {string}
*/
var userSettingsKey = 'userSettings';
/**
* Get the user settings
* Timeformat - 1 = international
* Timeformat - 2 = U.S
* @return {Object}
*/
UserSettings.getUserSettings = function () {
if (!userSettings) {
userSettings = localStorageService.get(userSettingsKey);
if (!userSettings)
//Default user settings
userSettings = {timeFormat: 1}
}
return userSettings;
};
/**
* Set the user settings object in the scope and in the local storage
* @param {Object}
*/
UserSettings.setUserSettings = function (settings) {
if (settings) {
var success = localStorageService.set(userSettingsKey, settings);
if (success)
userSettings = settings;
return success;
}
};
return UserSettings;
}]);
所选格式正在过滤器中激活
timeFormatFilter
/**
* Get a formatted text from timestemp
* It will return the time in the format that was set inside the UserSettings
*/
app.filter('timeFormatFilter', ['UserSettings', function (UserSettings) {
var userSettings;
/**
* @param time The time
* @param isDate if to return a string with a date
* @param isTime if to return a string with a time
*/
return function (time, isDate, isTime) {
var formattedTime = '';
if (!time)
return formattedTime;
userSettings = UserSettings.getUserSettings();
var utcTime = moment(time).utc();
if (isDate)
formattedTime = formattedTime + getDate(utcTime) + ' ';
if (isTime)
formattedTime = formattedTime + getTime(utcTime);
return formattedTime;
};
/**
* Get a date string in the format that is set inside the UserSettings
* @param utcTime
* @returns {string}
*/
function getDate(utcTime) {
var date = '';
switch (userSettings.timeFormat) {
case 1:
date = utcTime.format('DD/MM/YYYY');
break;
case 2:
date = utcTime.format('MM/DD/YYYY');
break;
}
return date;
}
/**
* Get a time string in the format that is set inside the UserSettings
* @param utcTime
* @returns {string}
*/
function getTime(utcTime) {
var time = '';
switch (userSettings.timeFormat) {
case 1:
time = utcTime.format('HH:mm');
break;
case 2:
time = utcTime.format('h:mm a');
break;
}
return time;
}
}]);
HTML:
{{startTime| timeFormatFilter:true:false}}
此过程正常,但在更改UserSettings后不会调用过滤器。我想以某种方式将过滤器激活绑定到UserSettings的更改。
我在这里看到了一些问题,但没有人回答我的问题。