與AngularJS和JS在一般情況下很新,所以裸露在我身邊。加載第一頁加載服務 - AngularJS
我得到了它處理日期格式轉換的簡單AngularJS服務:
'use strict';
angular.module('myApp')
.service('DateUtils', function() {
/**
* Convert US -> EU date format OR EU -> US data format
* @param date Date format yyyy-MM-dd OR dd-MM-yyyy
* @returns {*} opposite of input
*/
this.simpleDateFormatConverter = function (date) {
if (date) {
var benchmark = date.substr(0, 4);
// Check wether the first four digits are integers (US)
var matches = benchmark.match("^[0-9]*$");
// if the date is US simple date format (yyyy-MM-dd)
if (matches != null) {
var year = date.substr(0, 4);
var month = date.substr(5, 2);
var day = date.substr(8, 2);
// US -> EU
return day + "-" + month + "-" + year;
} else {
var year = date.substr(6, 4);
var month = date.substr(3, 2);
var day = date.substr(0, 2);
// EU -> US
return year + "-" + month + "-" + day;
}
} else {
return null;
}
}
});
案例:我有一個編輯頁面,正在充滿了實體的現有數據。 (在這種情況下,出生日期以美國格式)。在我的控制器中,如下所示,我正在注入該服務並使用其功能來轉換實體Author的birthDate。
訪問編輯頁面時,出生日期爲美國格式,但刷新頁面時,會按照希望進行轉換。
'use strict';
angular.module('myApp')
.controller('AuthorEditController',
['$scope', '$stateParams', 'entity', 'Author', '$state', 'DateUtils',
function ($scope, $stateParams, entity, Author, $state, DateUtils) {
$scope.error = null;
$scope.author = entity;
$scope.load = function (id) {
Author.get({id: id}, function (result) {
$scope.author = result;
});
};
// Only working on page reload
$scope.author.birthDate = DateUtils.simpleDateFormatConverter($scope.author.birthDate);
$scope.save = function() {
// save author
};
}]);
是否因爲我的數據尚未正確加載,因此當時未定義的數據不能被服務操縱?
我怎樣才能確保這是動態完成的第一頁加載?
由於提前,
小心使用線程通信ENT。 JavaScript是單線程的。回調將在同一個線程中調用,但在另一個時間。 –
是的,在技術分析中,JS腳步是假的並行。但通過編程方式,它將與線程相同,因此似乎沒有必要指出它。感謝您的領導! –
已經試過這個,不起作用 – Lobato