How to convert string to number or date in angularjs expression

ぃ、小莉子 提交于 2019-12-04 06:43:04

This way uses a directive to automagically converts numbers to string and viceversa. I mean using an input element type=number binded to a string variable.

This is done by using, $formatters and $parsers.

app.directive('numberConverter', function() {
  return {
    priority: 1,
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      function toModel(value) {
        return "" + value; // convert to string
      }

      function toView(value) {
        return parseInt(value); // convert to number
      }

      ngModel.$formatters.push(toView);
      ngModel.$parsers.push(toModel);
    }
  };
});

HTML

 <input type="number" number-converter ng-model="model.number">

More Information:

ngModel.$formatters

Array of functions to execute, as a pipeline, whenever the model value changes. Each function is called, in turn, passing the value through to the next. Used to format / convert values for display in the control and validation.

ngModel.$parsers

Array of functions to execute, as a pipeline, whenever the control reads value from the DOM. Each function is called, in turn, passing the value through to the next. The last return value is used to populate the model. Used to sanitize / convert the value as well as validation. For validation, the parsers should update the validity state using $setValidity(), and return undefined for invalid values.

PLUNKER

Source Documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!