2017-06-20 51 views
0

我用AngularJS 1.5和有一個對象,讓我們說:AngularJS - 創建自定義轉換器視圖

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 }},但我也需要對其進行編輯。

這可能是一個愚蠢的問題,但我是後端開發人員,還不習慣前端功能。感謝幫助!

回答

2

你可以使用類似下面的例子: 這是一個指令,使用格式化程序(模型 - >用戶)和解析器(用戶 - >模型)將文本轉換爲日期和日期文本。

(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> 
+1

謝謝你,會試試吧! – awfun