这是一个过滤货币字段的指令,因此用户只需要输入并隐含小数。
效果很好,除了我想允许负数。
http://plnkr.co/edit/qlZrc7dnZEUWzoNGyaF6?p=preview
我认为我可以拿出这一行:
var plainNumber = viewValue.replace(/[^-+0-9]/g, '');
但这样做违反了指令。任何人都知道如何更新它只允许数字和负号?
所以任何带字母的内容都会被替换为7987hjhd.00
,但-938.87
和8937.34
将被允许。
答案 0 :(得分:1)
此代码将最后两个数字的数字和格式设为小数。
键入+
和-
会更改符号。目前,它显示+
,但可以轻松更改。
你为什么不尝试看看我的意思:
var app = angular.module('App', []);
app.controller('MainCtrl', function($scope) {});
app.directive('inputRestrictor', [
function() {
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, element, attr, ngModelCtrl) {
// Matches characters that aren't `0-9`, `.`, `+`, or `-`
var pattern = /[^.0-9+-]/g;
function fromUser(text) {
var rep = /[+]/g; // find + symbol (globally)
var rem = /[-]/g; // find - symbol (globally)
rep.exec(text);
rem.exec(text);
// Find last index of each sign
// The most recently typed characters are last
var indexp = rep.lastIndex;
var indexm = rem.lastIndex;
// remove formatting, and add it back later
text = text.replace(/[+.-]/g, '');
if (indexp > 0 || indexm > 0) {// Are there signs?
if (indexp > indexm){ // plus sign typed later?
text = "+" + text;
} else text = "-" + text;
}
var transformedInput = text.replace(pattern, '');
transformedInput = transformedInput.replace(
/([0-9]{1,2}$)/, ".$1" // make last 1 or 2 digits the decimal
)
ngModelCtrl.$setViewValue(transformedInput);
ngModelCtrl.$render();
return transformedInput;
}
ngModelCtrl.$parsers.push(fromUser);
}
};
}
]);
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@1.3.0-rc.2" data-semver="1.3.0-rc.2" src=" https://code.angularjs.org/1.3.0-rc.2/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="App">
<div ng-controller="MainCtrl">
<input type="text" ng-model="inputValue" input-restrictor>
<input type="submit" ng-click="getdata()" />
</div>
</body>
</html>