Binding between input [date] and Moment.js in AngularJS

To formulate the question, I prepared a simplified example:

... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', ['$scope', function($scope) { $scope.selectedMoment = moment(); //...more code... }]); </script> 

Basically, I need a binding between the model (date.js date) and the view (input field [date]) for proper operation - the date input is updated when the model is updated, and vice versa. Apparently, trying the example above would result in an error if the model is not of type Date.

This is why I ask experienced AngularJs developers how I can implement this binding correctly?

Any advice appreciated.

+8
javascript angularjs momentjs
source share
5 answers

Create a directive that analyzes the date to the moment and formats the moment in time.

Main example below (for error handling extension)

 myApp.directive('momentInput', function () { return { link: function(scope, elm, attrs, ctrl) { ctrl.$parsers.push(function(viewValue) { return moment(viewValue); }); ctrl.$formatters.push(function(modelValue) { return modelValue.toDate(); }); }, require: 'ngModel' } }); 
+4
source share

You can create a filter, for example:

 myApp.filter('moment', function() { return function(input) { return moment(input); }; }); 

If you wish, you can pass arguments to the filter and force it to call various functions of the moment. Take a look at angular filters , make sure you come up with something that suits your needs.

+3
source share

None of the proposed solutions worked for me. I was in the same problem and solved:

 ... <input type="date" ng-model="selectedMoment" /> ... <script> angular.module('dateInputExample', []) .controller('DateController', ['$scope', function($scope) { $scope.selectedMoment = moment().toDate(); //...more code... var momentDate = moment($scope.selectedMoment); //...more code... }]); </script> 
+2
source share
 <input type="date" /> 

a string with a specific format or (possibly) a JavacSript Date () object is required. http://www.w3schools.com/html/html_form_input_types.asp

Therefore, you cannot use the momentjs object in this way.

If you want to get the string as a result, just use input with type="date" . If you want to have momentjs plus formatting and other things, you will have to create your own directive or filter.

0
source share

when send it, pull out the original format, changing it to a new one.

HTML

 <input type="date" ng-model="input.NewEventDate" > <button type="button" class="btn btn-success" ng-click="add()">submit</button> 

Javascript

 $scope.add = function(){ $scope.input.NewEventDate = moment($scope.input.NewEventDate).format("DD-MM-YYYY"); } 
0
source share

All Articles