AngularJS - 在自定义指令中呈现模板之前格式化ng-model

时间:2013-04-09 12:28:07

标签: templates model angularjs directive

我正在Angular JS中创建一个自定义指令。我想在模板渲染之前格式化ng-model。

这是我到目前为止所做的:

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>

我想在将unformattedDate值输入模板的ngModel之前格式化。像这样:

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

但这给了我一个错误。怎么做?

1 个答案:

答案 0 :(得分:25)

ngModel公开其控制器ngModelController API并为您提供了一种方法。

在你的指令中,你可以添加完全符合你需要的$formatters$parsers,它们会反过来(在它进入模型之前解析它)。

这是你应该去的方式:

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>'
  };
});
相关问题