2016-09-14 68 views
4

我得到这个错误The ng-model for md-datepicker must be a Date instance. Currently the model is a: string。我在模型md- datePicker - 日期实例错误总是

Contact.prototype.getSetIncorporated = function(date) { 
     if (arguments.length) { 
      this.company.information.incorporatedObject = date; 
      this.company.information.incorporated = moment.utc(date).format('X'); 
     } 
     if (!this.company.information.incorporatedObject) { 
      if (this.company.information.incorporated !== '') { 
       this.company.information.incorporatedObject = moment.utc(this.company.information.incorporated, 'X').toDate(); 
      } else { 
       this.company.information.incorporatedObject = null; 
      }} 
     return this.company.information.incorporatedObject; 
    } 

我也尝试了好几种mdLocale.formatDate和parseDate使用瞬间..

鉴于

<md-datepicker ng-model="Model.currentContact.getSetIncorporated" ng-model-options="{ getterSetter: true }" md-placeholder="Enter date"></md-datepicker> 

。目前的版本是

$mdDateLocale.formatDate = function(date) { 

      return moment(date).format('YYYY/MM/DD'); 
     }; 

     $mdDateLocale.parseDate = function(dateString) { 

      var m = moment(dateString, 'YYYY/MM/DD', true); 
      return m.isValid() ? m.toDate() : new Date(NaN); 
     }; 

当我说字符串转换为新的日期()Date对象的服务器发送该字符串2016-09-10T22:00:00.000Z

,我得到了mdDatePicker出正确的结果,但我得到的也 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! 这刹车我的页面。

回答

1

这很简单。您传递给​​的值是一个字符串而不是日期。

下面是一个问题的例子 - CodePen。控制台显示错误。

angular.module('MyApp',['ngMaterial']) 

.controller('AppCtrl', function() { 
    this.myDate = new Date(); 
    this.myDate = this.myDate.toString(); // Comment this out to work correctly 
}); 

这个问题 - How to check whether an object is a date? - 将解释如何查看是否在传递一个字符串或日期。

更新:

的原因消息

Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached.

似乎是因为Contact.prototype.getSetIncorporated返回一个日期。返回一个字符串的作品,但ng-model需要一个日期!

以下是解决该问题的一种方法 - CodePen

angular.module('MyApp',['ngMaterial']) 

.controller('AppCtrl', function($scope) { 
    this.myDate = new Date(); 

    this.test = function() { 
    return new Date(); 
    } 
    this.testModel = this.test(); 
}); 

标记

<div ng-controller="AppCtrl as vm" ng-cloak="" class="datepickerdemoBasicUsage" ng-app="MyApp"> 
    <md-content> 
    <md-datepicker ng-model="vm.testModel" ng-model-options="{ getterSetter: true }" ng-change="change()"></md-datepicker> 
    </md-content> 
</div> 
+0

我知道这是一个字符串...我甚至尝试转换该字符串与新的日期(stringDate),但得到无限的摘要循环错误。 – Alexa

+0

'未捕获错误:[$ rootScope:infdig] 10 $ digest()迭代到达。放弃!' – Alexa

+0

@Alexa - 您可能想补充说,您的问题可能是主要问题。 –

0

当您使用时刻,你必须从此刻采取_D属性:

var _convertStringToDate = function (stringDate) { 

     var date; 
     if (angular.isString(stringDate)) { 
      date = moment(stringDate)._d; 
     } 

     return date; 
    }; 
+0

我得到了 '未捕获的错误:[$ rootScope:infdig] 10 $ digest()迭代到达。中止!' – Alexa

+0

你可以发布你的代码吗? – milan