A
A
Anton2017-07-12 11:30:30
JavaScript
Anton, 2017-07-12 11:30:30

Two way date binding in Angular?

There is a variable with a date in unixstamp in $scope In the input template Question: What should I do to display the formatted date (For example, yyyy-mm-dd) And also when changing the input value (to the same format) what would $ scope.date was accepting the corresponding timestamp ?
$scope.date = 1499847985;
<input type="text" ng-model="date" />

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2017-07-12
@jezzit

This is usually done using parsers/formatters for ng-model.
Making a directive:

angular.module('foo').directive('dateTime', function() {
return {
   require: '^ngModel',
   link: linkFn,
};
function linkFn($element, $scope, $attrs, $ctrl) {
     // в $ctrl будет находиться ngModelController
     
     $ctrl.formatters.push(formatValue);
     $ctrl.parsers.push(parseValue);
      function formatValue(value) {
           // здесь делаем форматирование для отображения в DOM
          return formatedValue; 
      }
      function parseValue(value) {
           // здесь извлекаем из нового значения, которое пришло из DOM значение для ngModel
          return parsedValue;
      }
}
});

To work with dates (formatting and parsing), I recommend using moment.js
Doc about ngModelController here: https://docs.angularjs.org/api/ng/type/ngModel.NgM...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question