首先了解一下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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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); | |
}) | |
} | |
} | |
} | |
})(); |
js/controllers/formatter_parser.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
留言
張貼留言