本文介绍了在输入元素中使用 angularjs 过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我没有遗漏 doco 中的任何明显内容,如果有的话,我相信有人会提供帮助.

I hope I haven't missed anything obvious in the doco, if I have I'm sure someone will help.

我正在使用 asp.net webapi 返回带有日期字段的 DTO.这些使用 JSON.Net(格式为2013-03-11T12:37:38.693")进行序列化.

I'm using asp.net webapi to return a DTO, with date fields. These are serialized using JSON.Net (in format '2013-03-11T12:37:38.693').

我想在 INPUT 元素中使用过滤器,这是否可行,或者我应该创建一个新的过滤器或指令来完成此操作吗?

I'd like to use a filter but in an INPUT element, is this possible or should I create a new filter or directive to accomplish this?

// this just displays the text value
<input ui-datetime type="text" data-ng-model="entity.date" />
// this doesn't work at all
<input ui-datetime type="text" data-ng-model="{{entity.date|date:'dd/MM/yyyy HH:mm:ss a'}}" />
// this works fine
{{entity.date|date:'dd/MM/yyyy HH:mm:ss a'}}

有什么我遗漏的捷径吗?

Is there any shortcut I'm missing?

推荐答案

简而言之:如果您希望数据在视图和模型中具有不同的表示形式,则需要一个指令,您可以将其视为双向过滤器.

In short: if you want your data to have a different representation in the view and in the model, you will need a directive, which you can think of as a two-way filter.

你的指令看起来像

angular.module('myApp').directive('myDirective', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ngModelController) {
      ngModelController.$parsers.push(function(data) {
        //convert data from view format to model format
        return data; //converted
      });

      ngModelController.$formatters.push(function(data) {
        //convert data from model format to view format
        return data; //converted
      });
    }
  }
});

HTML:

<input my-directive type="text" data-ng-model="entity.date" />

这是一个有效的 jsFiddle 示例.

Here is a working jsFiddle example.

这篇关于在输入元素中使用 angularjs 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 19:59