2015-08-03 176 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

你可以建议我一种这种类型的字符串的方法,我是所有这些东西的新手。 –