forked from angular/code.angularjs.org
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdev_guide.templates.formatters.creating_formatters.html
49 lines (45 loc) · 1.79 KB
/
dev_guide.templates.formatters.creating_formatters.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<h1>Developer Guide: Templates: Angular Formatters: Creating Angular Formatters</h1>
<div class="developer-guide-templates-angular-formatters-creating-angular-formatters"><fieldset class="workInProgress"><legend>Work in Progress</legend>
This page is currently being revised. It might be incomplete or contain inaccuracies.</fieldset>
<p>To create your own formatter, you can simply register a pair of JavaScript functions with
<code>angular.formatter</code>. One of your functions is used to parse text from the input widget into the
data storage format; the other function is used to format stored data into user-readable text.</p>
<p>The following example demonstrates a "reverse" formatter. Data is stored in uppercase and in
reverse, but it is displayed in lower case and non-reversed. When a user edits the data model via
the input widget, the input is automatically parsed into the internal data storage format, and when
the data changes in the model, it is automatically formatted to the user-readable form for display
in the view.</p><div ng:non-bindable><pre class="brush: js;">
function reverse(text) {
var reversed = [];
for (var i = 0; i < text.length; i++) {
reversed.unshift(text.charAt(i));
}
return reversed.join('');
}
angular.formatter('reverse', {
parse: function(value){
return reverse(value||'').toUpperCase();
},
format: function(value){
return reverse(value||'').toLowerCase();
}
});
</pre></div><p><doc:example>
<doc:source></p>
<script type="text/javascript">
function reverse(text) {
var reversed = [];
for (var i = 0; i < text.length; i++) {
reversed.unshift(text.charAt(i));
}
return reversed.join('');
}
angular.formatter('reverse', {
parse: function(value){
return reverse(value||'').toUpperCase();
},
format: function(value){
return reverse(value||'').toLowerCase();
}
});
</script></div>