How to bind View Date to model milliseconds with Angularjs

10,520

Solution 1

I found a solution with :

ngModel.$parsers.push(fromUser);  
ngModel.$formatters.push(toUser);  

With that, i change dynamically the data format during the binding.

See full solution in jsfiddle

Solution 2

You can use ng-change https://docs.angularjs.org/api/ng/directive/ngChange

                $scope.onDateChange = function() {
                  if (this.node.mydate) {
                    this.node.mydate = this.node.mydate.getTime();
                  }
                };

And in the view

 <input type="text" ng-model="node.mydate" id="adate" name="adate" datepicker-popup="dd MMM yyyy HH:mm" ng-change="onDateChange()"/>

Solution 3

You can simply use it, it worked for me:

$scope.dateValue = new Date(dateInMilliSeconds);

It will directly convert your date in milliseconds to Date in MM/DD/YYYY format which is the default format for:

<input id="myDateID" name="myDateName" date-parser="MM/DD/YYYY" ng-model="dateValue" type="date"  class="form-control input-md" aria-describedby="sizing-addon3"/>
Share:
10,520
asicfr
Author by

asicfr

Updated on June 16, 2022

Comments

  • asicfr
    asicfr almost 2 years

    I want to bind an input of type Date on the view
    to a milliseconds property in the model with Angularjs.

    For example :
    the user set "09/23/2014" into the field
    and angularjs automatically set "1411423200000"
    into the model property binding with the input.

    I don't find any directive or filter to do that.

    Thanks for your help.


    UPDATE to detail my question.

    Is there a "native" way in Angularjs to intercept
    model to view AND view to model and convert my data ?