2015-08-03 178 views
0

我在我的項目中使用了angularjs。我從後端獲取日期字符串。日期字符串可以是任何可能是日期或可能不是日期的字符串。當我設置日期字符串ng-model如果它是一個日期字符串,然後它的工作細別的它拋出一個異常如何處理錯誤:ngModel:datefmt模型不是日期對象

Error: [ngModel:datefmt] http://errors.angularjs.org/1.4.3/ngModel/datefmt?p0=asdfdaf 
    at Error (native) 
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:6:416 
    at Array.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:167:250) 
    at Object.<anonymous> (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:264:75) 
    at n.$get.n.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:132:124) 
    at n.$get.n.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:135:269) 
    at http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:19:437 
    at Object.e [as invoke] (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:39:156) 
    at d (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:19:358) 
    at Ac (http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js:20:151) 

我不知道該如何處理這個異常。我正在考慮編寫一個像isDate(dateString)這樣的方法,但我不知道我應該在裏面寫什麼,因爲日期字符串可以是任何格式的任何字符串。請幫助我創建了plunkr here

+0

前段時間我有這個問題,你介意一下crossbrowser的兼容性嗎?在Firefox,Chrome和Safari瀏覽器中檢查你的運行... – gr3g

+0

我正在登陸chrome –

回答

1

當您的輸入設置爲鍵入日期時,angularJS將只接受JavaScript中的Date對象。

但是,當你的輸入有一個type =「date」時,chrome有一個特殊的功能,可以正確地呈現,但這不是其他瀏覽器的情況。

的解決方案是使用一個字符串...,並將其轉換

+0

你可以使用字符串,它在Date對象傳遞給Date構造函數時返回Date對象。 – dhavalcengg

+0

事實上,在我的情況下,這取決於是否需要與日期(用戶和邏輯) – gr3g

+0

yeah約定的很多交互,總是最好有一個值的單一類型。 – dhavalcengg

1

你可以有這樣的

function isValidDate(date) { 
    return !! (Object.prototype.toString.call(date) === "[object Date]" && +date); 
} 

一個自定義的方法沒有爲你的錯誤在角站點的說明

All date-related inputs like require the model to be a Date object. If the model is something else, this error will be thrown. Angular does not set validation errors on the in this case as those errors are shown to the user, but the erroneous state was caused by incorrect application logic and not by the user.

這意味着,如果您使用type =「date」,那麼您的ng模型應該是Date對象或可以轉換爲Date對象的某個字符串值。

+0

它將字符串'10/31/1997 23:00'返回'false'。正如我告訴你的,字符串可以是任何字符串。有沒有解決方案? –

+0

這是您的自定義字符串。你可以有自定義的方法,它可以將你的字符串轉換爲JavaScript Date對象。 Angular無法理解你的日期字符串。 – dhavalcengg

+0

你可以建議我一種這種類型的字符串的方法,我是所有這些東西的新手。 –