在Angularjs格式输入值 [英] Format input value in Angularjs
问题描述
我试图写一个指令,自动格式化的℃的号码;输入>
,但该模型未格式化。
得到它的工作是好的,对输入的值显示为1,000,000控制器百万负荷,但是打字只有 ngModel。$解析器
功能触发时。
当,当该指令被加载,当值是0, ngModel。$格式化
火是唯一一次。
怎样才能使它在关键preSS工作(我试过结合键preSS / KEYUP,但它不工作)。
下面是我的code:
angular.module('myApp.directives',[])。指令(filterInput',['$过滤',函数($过滤器){
返回{
限制:'A',
要求:'ngModel',
链接:功能(范围,元素,属性ngModel){ ngModel。$ parsers.push(功能FROMUSER(文本){
返回parseInt函数(text.replace(,,));
}); ngModel。$ formatters.push(功能TOUSER(文本){
的console.log($过滤器(数字)(文本));
返回($过滤器(数字)(文本||''));
}); }
};
}]);
下面是工作的例子在这里我们使用不印字
:
angular.module('myApp.directives',[])。指令('格式',['$过滤',函数($过滤器){
返回{
要求:'?ngModel',
链接:功能(范围,ELEM,ATTRS,CTRL){
如果(CTRL!)回报;
Ctrl键。$ formatters.unshift(函数(){
返回$过滤器(attrs.format)(Ctrl键。$ modelValue)
});
Ctrl键。$ parsers.unshift(功能(viewValue){
变种plainNumber = viewValue.replace(/ [^ \\ D | \\ - + | \\ +] /克,'');
elem.val($滤波器(attrs.format)(plainNumber));
返回plainNumber;
});
}
};
}]);
中的HTML似乎:
<输入类型=文本NG模型=测试格式=号/>
请参阅演示<大骨节病> 小提琴 骨节病>
希望其帮助
I'm trying to write a directive that automatically formats a number in the <input>
but the the model isn't formatted.
Getting it to work is fine, on load the value in the input is displayed as 1,000,000 and 1000000 in the controller, however when typing only the ngModel.$parsers
function fires.
The only time when the ngModel.$formatters
fire is when the directive gets loaded and when the value is 0.
How can I make it work on keypress(I've tried binding to keypress/keyup but it doesn't work).
Here's my code:
angular.module('myApp.directives', []).directive('filterInput', ['$filter', function($filter) {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModel) {
ngModel.$parsers.push(function fromUser(text) {
return parseInt(text.replace(",", ""));
});
ngModel.$formatters.push(function toUser(text) {
console.log($filter('number')(text));
return ($filter('number')(text || ''));
});
}
};
}]);
Here is working example where we use unshift
:
angular.module('myApp.directives', []).directive('format', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.format)(ctrl.$modelValue)
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter(attrs.format)(plainNumber));
return plainNumber;
});
}
};
}]);
The HTML seems:
<input type="text" ng-model="test" format="number" />
See Demo Fiddle
Hope its help
这篇关于在Angularjs格式输入值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!