首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在自定义指令中呈现模板之前的AngularJS格式化ng模型

在自定义指令中呈现模板之前的AngularJS格式化ng模型
EN

Stack Overflow用户
提问于 2013-04-09 20:28:07
回答 1查看 10.6K关注 0票数 11

我正在用Angular JS创建一个自定义指令。并且我想在模板呈现之前格式化ng-model。

这就是我到目前为止所知道的:

app.js

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

html

代码语言:javascript
复制
<edit-in-place ng-model="unformattedDate"></edit-in-place>

我希望在将unformattedDate值输入到模板的ngModel之前对其进行格式化。如下所示:

代码语言:javascript
复制
template: '<input type="text" ng-model="formatDate(ngModel)" my-date-picker disabled>'

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

EN

回答 1

Stack Overflow用户

发布于 2013-04-09 20:44:41

ngModel公开了它的控制器ngModelController API,并为您提供了这样做的方法。

在您的指令中,您可以添加$formatters$parsers,后者执行相反的操作(在值进入模型之前对其进行解析)。

下面是你应该怎么做:

代码语言:javascript
复制
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>'
  };
});
票数 25
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/15901889

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档