[英]How do you Dynamically format an input field text as you type into that same field using angularjs
http://jsfiddle.net/crimsonalucard/238u6/ http://jsfiddle.net/crimsonalucard/238u6/
javascript: 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: 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. 请参阅上面的JSFiddle。 I want the text in the input field to dynamically update itself with the formatting seen in $scope.time.
我希望输入字段中的文本使用$ 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). 所以基本上当我在输入字段中键入(0000000)时,我希望输入字段本身(不仅仅是$ scope.time)动态更改以匹配我将$ scope.time格式化为(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.
我意识到angular-UI mask指令是一个可能的解决方案,但这不是我正在寻找的。
You could use AngularUI's Mask directive. 您可以使用AngularUI的Mask指令。 http://angular-ui.github.io/
http://angular-ui.github.io/
There is also is a discussion here on the topic with an example. 此处还讨论了该主题的一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.