我创建的指令使用函数 setFormatting 来屏蔽输入字段中的文本值。
scope.$watch(element, function() {
modelCtrl.$setViewValue(setFormatting(element.val(), attrs.symbol));
modelCtrl.$render();
});
element.bind('blur', function() {
modelCtrl.$setViewValue(setFormatting(element.val(), attrs.symbol));
modelCtrl.$render();
});
scope.$watch 在第一次加载/应用内容时应用掩码,element.bind 在其他时间应用掩码。 scope.$watch 将符号(如果有)存储为 ng-model 变量的一部分。 element.bind 不是。我认为 $setViewValue() 和 $render() 没有更新 ng-model 变量。变量在哪里更新?
参见附件:http://jsfiddle.net/PJ3M4/
谢谢。
最佳答案
这里我们使用了$formatters.unshift
和$filter
:
JS
var fessmodule = angular.module('myModule', []);
fessmodule.controller('fessCntrl', function ($scope) {
$scope.test = 123456879;
});
fessmodule.$inject = ['$scope'];
fessmodule.directive('format', ['$filter', function ($filter) {
return {
require: '?ngModel',
link: function (scope, elem, attrs, ctrl) {
if (!ctrl) return;
var symbol = "°"; // dummy usage
ctrl.$formatters.unshift(function (a) {
return $filter(attrs.format)(ctrl.$modelValue) + symbol;
});
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+|\.+]/g, '');
elem.val($filter('number')(plainNumber) + symbol);
return plainNumber;
});
}
};
}]);
HTML
<input type="text" ng-model="test" format="number"/>
演示 Fiddle
作为旁注
您会发现这也很有帮助:Fiddle
关于AngularJS 指令数字格式屏蔽,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19861408/