这是插件链接-> http://plnkr.co/edit/iFnjcq?p=preview
正如您在链接中看到的,它执行输入字段的验证。只允许输入数字,它会自动添加逗号。
我的问题是->如果我在该字段中给出一个负数,我如何自动更改该字段中输入的值的颜色。
即正数应按原样显示。当用户输入负数时,数字会以红色文本输入。
我有什么办法可以达到这个目标吗??
HTML-
<div ng-controller="MainCtrl">
<input type="text" ng-model="amount" format="number" />
</div>
JS指令
var app = angular.module('App',[]);
app.controller('MainCtrl', function ($scope) {
});
app.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('number')(plainNumber/100,2));
return plainNumber;
});
}
};
}]);
关于下面讨论的样式覆盖问题,问题就在这里。
实际的HTML代码
<div class="Ip"><input type="text" ng-model="amount" format="number" /></div>
CSS 是通过 scss 为类 Ip 应用的。在这里
$font:#fff; //this font gets overwritten. even if i exclude this font of bootstrap is there which will overwite the class mentioned in directive.
.inputCl{
color:$font;
}
.Ip{
input{
@extend .inputCl;
}
}
最佳答案
当您应用格式时,只需检查它是否为负数并根据需要添加一个 css 类
ctrl.$parsers.unshift(function (viewValue) {
var plainNumber = viewValue.replace(/[^\d|\-+]/g, '');
elem.val($filter('number')(plainNumber/100,2));
if (plainNumber < 0) {
elem.addClass('negative');
} else {
elem.removeClass('negative');
}
return plainNumber;
});
http://plnkr.co/edit/GdneR70Rw6RtTbwMrfx4?p=preview
你的 SASS
$font:#fff;
$fontNegative:#ff0000;
.inputCl{
color:$font;
}
.Ip{
input{
@extend .inputCl;
}
input.negative {
color: $fontNegative;
}
}
关于javascript - 输入字段的样式字体(Angularjs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34095375/