I am using AngularUI to format or "masking" a phone number input, and it works fine with a ng-model:
<input ng-model="emer.phone" ui-mask="{{'(999) 999-9999'}}" type="text"/>
Question: But now how can I apply the same mask in the same way using ng-bind, I have something like this:
<td>{{emer.phone}}</td>
My problem: The ng-model and ng-bind are in two different files in different locations, therefor the use of "$viewValue" is not an option for me
Any idea?
some documentation about AngularUI mask: http://angular-ui.github.io/ui-utils/
Thanks!
You should use ui-mask="(999) 999-9999"
instead of ui-mask="{{'(999) 999-9999'}}"
.
The latter tries to bind to a model with '(999) 999-9999'
on it.
Instead of making your own masking or perhaps building your own directive you can make use of existing solutions.
Take tel.js for example. It is an input[tel] directive that formats and validates international phone numbers for you.
You can install it from bower like this:
bower install teljs --save
Then:
Link the two script files found in the 'src' folder: tel.js and metadatalite.js.
<script src="bower_components/teljs/src/tel.js"></script>
<script src="bower_components/teljs/src/metadatalite.js"></script>
Load the tel.js module.
angular.module('<your module>', ['teljs']);
You can try out tel.js here:
http://michaelkrog.github.io/tel.js/
Remark: I am the developer of tel.js.
SO far I couldn't find a simple solution using AngularUI mask, so I had to create a filter. I follow this: Format telephone and credit card numbers in AngularJS
And here is the jsfiddle: http://jsfiddle.net/jorgecas99/S7aSj/
angular.module('ng').filter('tel', function () {
return function (tel) {
if (!tel) { return ''; }
var value = tel.toString().trim().replace(/^\+/, '');
...
Cheers!
I can see in the ui-mask
demo, they cheat a bit and use the $viewValue
from ngModelController
.
So, you could try the same thing.
First, you must add a name to your input field and be wrapped in a form (with a name):
<form name="demo">
<input name="emerPhone" ng-model="emer.phone" ui-mask="{{'(999) 999-9999'}}" type="text"/>
<td>{{demo.emerPhone.$viewValue}}</td>
</form>
As you can see from the above example, the display code becomes:
<td>{{demo.emerPhone.$viewValue}}</td>
It would have been better if they would have provided a filter as well, though.
Also, I can see that in the demo for ui-mask, they show and hide based on the length
of the $viewValue
:
<div ng-show="demo.masked.$viewValue.length">NgModelController.$viewValue: <code>{{ demo.masked.$viewValue
}}</code></div>
<div ng-hide="demo.masked.$viewValue.length">NgModelController.$viewValue: <code>undefined</code></div>
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With