javascript - 输入字段的样式字体(Angularjs)

标签 javascript jquery css angularjs validation

这是插件链接-> 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/

相关文章:

javascript - 异步包含的 div 的 jQuery Mobile 样式

javascript - <div> 元素页脚白色背景

javascript - Jquery:使用唯一键名称迭代嵌套 JSON

javascript - 某种 "method"用于读取元素是在两页还是一页上

css - 使 div 的高度与其在 Bootstrap 中的宽度相同

javascript - Iframe 图片默认缩小问题

javascript - 使用 javascript 定位 DIV 的 style.left 不起作用

javascript - 如何将 ng-model 添加到动态创建的输入文本字段

javascript - 检查 jquery 中的 url 参数并将某些内容附加到 url

javascript - 更改值时防止 slider 跳跃