AngularJS - Formatting ng-model before template is rendered in custom directive

一笑奈何 提交于 2019-11-29 02:53:24

问题


I am creating a custom directive in Angular JS. And I want to format the ng-model before the template renders.

This is what I have so far:

app.js

app.directive('editInPlace', function() {
    return {
        require: 'ngModel',
        restrict: 'E',
        scope: { ngModel: '=' },
        template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
    };
});

html

<edit-in-place ng-model="unformattedDate"></edit-in-place>

I want to format the unformattedDate value before it is entered in the ngModel of the template. Something like this:

template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'

but that gives me an error. How to do this?


回答1:


ngModel exposes its controller ngModelController API and offers you a way to do so.

In your directive, you can add $formatters that do exactly what you need and $parsers, that do the other way around (parse the value before it goes to the model).

This is how you should go:

app.directive('editInPlace', function($filter) {
  var dateFilter = $filter('dateFormat');

  return {
    require: 'ngModel',
    restrict: 'E',
    scope: { ngModel: '=' },
    link: function(scope, element, attr, ngModelController) {
      ngModelController.$formatters.unshift(function(valueFromModel) {
        // what you return here will be passed to the text field
        return dateFilter(valueFromModel);
      });

      ngModelController.$parsers.push(function(valueFromInput) {
        // put the inverse logic, to transform formatted data into model data
        // what you return here, will be stored in the $scope
        return ...;
      });
    },
    template: '<input type="text" ng-model="ngModel" my-date-picker disabled>'
  };
});


来源:https://stackoverflow.com/questions/15901889/angularjs-formatting-ng-model-before-template-is-rendered-in-custom-directive

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