跳到主要內容

angular formatters and parsers


首先了解一下ng-model controller中的兩個屬性


  • $viewValue: 顯示給使用者的值
  • $modelValue: model背後所綁定的值

說明


  • $parsers - change $viewValue
  • $formatters - change $modelValue

範例


  • design displayDate directive - format YYYY/MM/DD to display
  • controller define dateTime、dateFormat to binding
  • html binding
  • Demo
  • Source code

js/directives/directives.js

'use strict';
(function() {
angular.module('notes')
.directive('displayDate', [displayDate])
function displayDate() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attrs, ngModelCtrl) {
//format text from the user (view to model)
ngModelCtrl.$parsers.push(function(data) {
return moment(new Date(data)).format();
});
//format text going to user (model to view)
ngModelCtrl.$formatters.push(function(data) {
return moment(new Date(data)).format(attrs.format);
})
}
}
}
})();
view raw directives.js hosted with ❤ by GitHub

js/controllers/formatter_parser.js

'use strict';
(function() {
angular.module('notes')
.controller('formatterParserController', [formatterParserController])
function formatterParserController() {
var self = this;
self.dateFormat = 'YYYY-MM-DD';
self.dateTime = new Date();
}
})();

views/formatter_parser.html

<div class="table-responsive">
<table >
<tbody class="no-borders">
<tr>
<td>
<h3 class="control-label">Date Time Picker: </h3>
</td>
<td>
<input class="form-control"
format=""
ng-model="formatterParserCtrl.dateTime"
display-date />
</td>
</tr>
<tr>
<td>
<h3 class="inline">Model Value: </h3>
</td>
<td>
</td>
</tr>
</tbody>
</table>
</div>

留言

這個網誌中的熱門文章

C#資料庫操作(新增、修改、刪除、查詢)

java西元民國轉換_各種不同格式