Angularjs 中的 4 位数字格式
4 digit number formatting in Angularjs
我的应用程序有这样的要求——用户在文本框字段中键入一个值,并在下面的框中并行显示。但问题是我想要这样的格式 1234-1234-1234 (包括破折号)。这可能吗。我试过使用 angular 过滤器,但似乎不起作用。
假设您正在使用 Angular 1.X,我建议您为此创建一个指令,以便更好地控制元素。
试试下面
var app = angular.module('TestApp', []);
app.directive('inputFormat', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="inputVal" placeholder="Enter a number" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
var inputElm = elem.val().split("-").join(""); // remove hyphens
if (inputElm.length > 0) {
inputElm = inputElm.match(new RegExp('.{1,4}', 'g')).join("-");
}
elem.val(inputElm);
});
}
};
});
app.controller('MyCtrl', function($scope) {
$scope.search = function(element) {
console.log(element);
alert("keypressed. Value so far is: " + element.val());
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="MyCtrl">
<input-format/>
</div>
</div>
这是http://jsfiddle.net/anandgh/6unogzyh/
希望对您有所帮助
我的应用程序有这样的要求——用户在文本框字段中键入一个值,并在下面的框中并行显示。但问题是我想要这样的格式 1234-1234-1234 (包括破折号)。这可能吗。我试过使用 angular 过滤器,但似乎不起作用。
假设您正在使用 Angular 1.X,我建议您为此创建一个指令,以便更好地控制元素。
试试下面
var app = angular.module('TestApp', []);
app.directive('inputFormat', function() {
return {
restrict: 'AE',
replace: true,
template: '<input type="text" ng-model="inputVal" placeholder="Enter a number" />',
link: function(scope, elem, attrs) {
elem.bind('keyup', function() {
var inputElm = elem.val().split("-").join(""); // remove hyphens
if (inputElm.length > 0) {
inputElm = inputElm.match(new RegExp('.{1,4}', 'g')).join("-");
}
elem.val(inputElm);
});
}
};
});
app.controller('MyCtrl', function($scope) {
$scope.search = function(element) {
console.log(element);
alert("keypressed. Value so far is: " + element.val());
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="TestApp">
<div ng-controller="MyCtrl">
<input-format/>
</div>
</div>
这是http://jsfiddle.net/anandgh/6unogzyh/
希望对您有所帮助