There is this requirement for my application where-in the user types a value in the text box field and parallely shown in a box below. BUT the problem is I want to have format something like this 1234-1234-1234 (including the dashes). Can that be possible. I've tried using the angular filters but seems to be not working.
-
You can use input mask plugin for easily do thatbipin patel– bipin patel2018-02-27 06:02:11 +00:00Commented Feb 27, 2018 at 6:02
-
Which version of angular is this? also show the code that you tried so far?Anand G– Anand G2018-02-27 06:31:39 +00:00Commented Feb 27, 2018 at 6:31
-
Where is your attempt what already you have tried??A.A Noman– A.A Noman2018-02-27 06:35:57 +00:00Commented Feb 27, 2018 at 6:35
Add a comment
|
1 Answer
Assuming you are using Angular 1.X, I would suggest you to create a directive for this which will give a better control on the element.
Try below
var app = angular.module('TestApp', []);
app.directive('inputFormat', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="inputVal" placeholder="Enter a number" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
var inputElm = elem.val().split("-").join(""); // remove hyphens
if (inputElm.length > 0) {
inputElm = inputElm.match(new RegExp('.{1,4}', 'g')).join("-");
}
elem.val(inputElm);
});
}
};
});
app.controller('MyCtrl', function($scope) {
$scope.search = function(element) {
console.log(element);
alert("keypressed. Value so far is: " + element.val());
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="MyCtrl">
<input-format/>
</div>
</div>
Here is the http://jsfiddle.net/anandgh/6unogzyh/
Hope this helps
1 Comment
Prudhvi Bharadwaj
Thank you very much sir. The code is working so perfectly.