当您使用angularjs键入同一字段时,如何动态格式化输入字段文本

Bri*_*Yeh 4 javascript 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;
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

请参阅上面的JSFiddle.我希望输入字段中的文本使用$ scope.time中的格式动态更新自身.怎么做?

所以基本上当我在输入字段中键入(0000000)时,我希望输入字段本身(不仅仅是$ scope.time)动态更改以匹配我将$ scope.time格式化为(0:00:00:00) .

(编辑:)我想解决方案除了角本身之外不使用任何其他库.我意识到angular-UI mask指令是一个可能的解决方案,但这不是我正在寻找的.

rga*_*ill 5

您可以使用AngularUI的Mask指令.http://angular-ui.github.io/

此处还讨论该主题的一个例子.