AngularJS - 为视图创建自定义转换器

AngularJS - create custom converter for a view

我使用 AngularJS 1.5 并有一个对象,比方说:

myObject = {
  ts: 1497971053529, //time in ms
  field: { a: b } //some object
}

我希望用户观察和编辑 myObject 的字段,但我想将 ts 显示为日期(天,yyyy.mm.dd),field 应该在 json 中。类似的东西:

<input type="text" ng-model="myObject.ts"
    wtf-to-converter="longToDate" wtf-from-converter="dateToLong">
<input type="text" ng-model="myObject.field"
    wtf-to-converter="objectToJson" wtf-from-converter="jsonToObject">

结果:

2017.06.20
{"a":"b"}

那么如何实现这些转换器呢?如果我只需要观察这些值,我可以使用 AngularJS 管道:{{myObject.field | json }},但我也需要对其进行编辑。

这可能是个愚蠢的问题,但我是后端开发人员,还不习惯前端功能。感谢您的帮助!

您可以使用类似于以下示例的内容: 这是一个使用格式化程序(模型 -> 用户)和解析器(用户 -> 模型)将文本转换为日期和日期转换为文本的指令。

(function (angular) {
    "use strict";

    angular.module("YourModule").directive("msDate", msDate);

    function msDate() {
        return {
            restrict: "A",
            require: "ngModel",
            link: link
        };

        function link(scope, element, attrs, ngModel) {
            // From the user to the model
            ngModel.$parsers.push(function (value) {
                return new Date(value).getTime();
            });
            // From the model to the user
            ngModel.$formatters.push(function (value) {
                return new Date(value);
            });
        }
    }
}(angular));

这不是您问题的完整解决方案,但您会明白的;

用法是这样的:

<input type="date" ng-model="yourModel" ms-date>