Md- datePicker - date instance error always

I get this error The ng-model for md-datepicker must be a Date instance. Currently the model is a: string. I use the moment ..

in sight

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

in the model

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;
    }

I also tried several mdLocale.formatDate and parseDate. Current version

$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);
        };

the server sends this line 2016-09-10T22:00:00.000Z

When I convert this string to a Date object with a new Date (), I get the correct result displayed in mdDatePicker, but I also get Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting! which slows down my page.

+4
source share
2 answers

It is pretty simple. The value you pass to Model.currentContact.getSetIncorporatedis a string, not a date.

- CodePen. .

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

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

- , ? - , , .

Update:

: [$ rootScope: infdig] 10 $digest() .

, 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>
+1

, _d :

    var _convertStringToDate = function (stringDate) {

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

        return date;
    };
0

Source: https://habr.com/ru/post/1654579/


All Articles