Brian Yeh
Brian Yeh

Reputation: 3247

How do you Dynamically format an input field text as you type into that same field using angularjs

http://jsfiddle.net/crimsonalucard/238u6/

javascript:

var myModule = angular.module('myModule', []);

myModule.controller('myController', function($scope){
});

myModule.directive('addColons', function(){
    return{
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel){
            ngModel.$parsers.push(addColons);
            ngModel.$formatters.push(addColons);
        }
    };
});

function insert(text, insertion, index)
{
    return text.slice(0,index) + insertion + text.slice(index);
}

function addColons(text)
{

    if(text.length !== undefined)
    {
        console.log("length is: " + text.length);
        for(var i = text.length-2; i>0; i-=2)
        {
            if(text.charAt(i) !== ':')
            {
                text = insert(text, ":", i);
            }
        }
    }
    return text;
}

HTML:

<div ng-app="myModule">
    <div ng-controller="myController">
        <input add-colons type="text" ng-model="time"/>
        <p>How do I get the text in the input field above to dynamically change to be equivalent to the string below as I am typing?</p>
        <p>$scope.time = {{time}}</p>
    </div>
</div>

See the JSFiddle above. I want the text in the input field to dynamically update itself with the formatting seen in $scope.time. How would this be done?

So essentially as I type (0000000) into the input field I want the input field itself (Not just $scope.time) to dynamically change to match what I'm formatting $scope.time into (0:00:00:00).

(edit:) I would like the solution to not utilize any other libraries besides angular itself. I realize the angular-UI mask directive is a possible solution but this is not what I'm looking for.

Upvotes: 4

Views: 3983

Answers (1)

rgaskill
rgaskill

Reputation: 2067

You could use AngularUI's Mask directive. http://angular-ui.github.io/

There is also is a discussion here on the topic with an example.

Upvotes: 5

Related Questions