Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

In order to formulate question I prepared the 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 just need binding between model(moment.js's date) & view(input[date] field) to work properly - date input is updated when model is updated and vice versa. Apparently, trying the example above would bring you error that model is not of the Date type.

That's why I am asking experienced AngularJs developers, how can I implement this binding properly?

Any advices appreciated.

like image 499
ialekseev Avatar asked Nov 25 '14 13:11

ialekseev


3 Answers

Create a directive which parses date to moment and formats moment to date.

Basic example below (to be extended with error handling)

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'
    }
});
like image 189
Wouter Seyen Avatar answered Nov 16 '22 22:11

Wouter Seyen


You can create filter, like this:

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

Optionally you can pass arguments into filter and make it call various moment functions. Take a look into angular filters , im sure you'll think of something that suits your needs.

like image 3
Goran Lepur Avatar answered Nov 16 '22 21:11

Goran Lepur


None of the proposed solutions worked for me. I've been in the same problem and solved with:

...
<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>
like image 3
David Avatar answered Nov 16 '22 22:11

David