我有以下变量:
$scope.pixelWidth = "30px";
我有一个像这样的输入框:
<input ng-model="pixelWidth" />
我希望输入框内仅包含数字,但在键入时仍将 px 插入 $scope.pixelWidth
中。
有办法实现这一点吗?
最佳答案
是的,您需要创建一个指令并将格式化程序和解析器添加到 ngModelController 。请参阅working version on plunker
指令:
app.directive('modelSuffix', [function() {
return {
restrict: 'AE',
require: '^ngModel',
link: function(scope, element, attributes, ngModelController) {
var suffix = attributes.modelSuffix;
// Pipeline of functions called to read value from DOM
ngModelController.$parsers.push(function(value) {
return value + suffix;
});
// Pipeline of functions called to display on DOM
ngModelController.$formatters.push(function(value) {
return value.replace(suffix, '');
});
}
}
}]);
像这样使用它:
<input ng-model="pixelWidth" model-suffix="px"/>
关于javascript - ng-model 在输入和显示时操纵值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31331369/