Change the input field font style in AngularJS

Check out this Plunker link for validation of input field: http://plnkr.co/edit/iFnjcq?p=preview

The validation only allows numbers to be entered and automatically adds commas. My query is, if a negative number is entered in the field, how can I change the color of that value to red?

In other words, positive numbers should appear normally, but when a negative number is entered, the text color should turn red.

Is there a way to achieve this functionality?

Here is the HTML code snippet:

<div ng-controller="MainCtrl">
  <input type="text" ng-model="amount" format="number" />
</div>

And here's the JavaScript directive code:

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;
        });
    }
};
}]);

Regarding the style override concern mentioned below, here is the issue:

The actual HTML code contains:

<div class="Ip"><input type="text" ng-model="amount" format="number" /></div>

The CSS is applied through SCSS for the class Ip. Here is the relevant snippet:

$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;                         
}

}

Answer №1

To ensure proper formatting, always check for negative values and apply a CSS class accordingly

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

Your SASS

$font:#fff; 
$fontNegative:#ff0000;   

.inputCl{
    color:$font;
}

.Ip{                     
    input{
          @extend .inputCl;                         
    }
    input.negative {
         color: $fontNegative;    
    }

}

Answer №2

To enhance your current format directive, consider adding a few conditions, though it may not be ideal. Directives are best when they are focused on performing a single task, such as formatting.

Instead, you could create a separate simple directive specifically for applying a new validation rule. Let's name this directive positive:

.directive('positive', [function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            if (!ctrl) return;
            ctrl.$validators.positive = function(value) {
                return value && value >= 0;
            };
        }
    };
}]);

Then, you would use it like this:

<input type="text" ng-model="amount" format="number" positive />

With this in place, you can style the valid/invalid states of the input by utilizing the .ng-invalid-positive class that Angular will apply based on the input's status:

.ng-invalid-positive {
    color: red;
}

Check out the demo here: http://plnkr.co/edit/2RAlx0DoFH1HEmdT0XCv?p=preview

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with jQuery Validation's require_from_group not functioning for specified class

I am struggling to properly implement require_from_group in this example form by applying it to the class instead of the name attribute. Any advice on what I might be overlooking? <h1>Form Validation Example</h1> <form id='registerForm ...

Can you please provide a method for determining which characters are adjacent to each other

I am in the process of developing a markdown editor and I require a check to identify if adjacent characters are specific characters, removing them if they match or adding them otherwise. For example, if the selected text is surrounded by two asterisks li ...

Is transitioning from AngularJS to Angular truly imperative?

We currently have a project built with AngularJS, but its support is ending and there are potential security vulnerabilities (CVEs) present. Do we need to transition to a different framework? Our project primarily involves front end development with data b ...

Utilizing JQuery for real-time total updates

When a new div is created by clicking a button, I want to dynamically maintain an order system where the first div is labeled as 1 of 1, then as more divs are added it should change to 1 of 2, and so on. If a div is deleted, the numbering should reset back ...

Is it possible to display one division on top of another with a transparent opacity effect in HTML?

I'm struggling with designing web pages and currently working on a page on codepen.io using code from this link. <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1 ...

Blend multiple images using Angular

Is there a way to combine multiple images in Angular? I came across some HTML5 code that seemed like it could do the trick, but unfortunately, I couldn't make it work. <canvas id="canvas"></canvas> <script type="text/javascript"> ...

Comparing dates in JavaScript using the built-in Date object

Currently, I am attempting to compare the current date with the one stored in a database using the code snippet below: <script> $("#registerButton").click(function() { var first = $("#scantime").val(); var second = $("#scanbartime").val(); if (parse ...

Using AngularJS, complete and send in the form

What is a simpler way to submit a form using AngularJS without utilizing an angular ajax call or adding the action="xxxx" attribute to the form? An example scenario could be a large form where assigning a model for each field isn't feasible, and send ...

What is the process of changing a number to the double data type in JavaScript or TypeScript?

Within a single input field, users can enter various numbers such as 12, 12.1, 12.30, and 12.34. The challenge is to pass this value in a service call where only the value can be sent as a number but with two decimal points. let a = input //a will be a ty ...

Guide to extracting information from a Node.js http get call

I am currently working on a function to handle http get requests, but I keep running into issues where my data seems to disappear. Since I am relatively new to Node.js, I would greatly appreciate any assistance. function fetchData(){ var http = requir ...

managing websocket connections across various instances

Looking to grasp the concept of managing websockets across multiple instances in order for it to be accessible by all instances. For example, with three nodes running connected through a load balancer, data needs to be emitted on a specific socket. My init ...

Replace the ngOnDestroy method

Is there a way to complete an observable when the ngOnDestroy is triggered? I'd prefer not to create new child components when dealing with just one component instance. I attempted to override ngOnDestroy by modifying the function in the component&apo ...

Is it recommended to utilize the jQuery Ajax API within jQueryMobile?

Currently, I am in the process of developing a Mobile web application using HTML5, CSS3, JavaScript, and jQueryMobile. I will then encapsulate it with Phonegap. As someone who is new to web development, I find myself pondering whether when utilizing jQuer ...

Modify the color of the text for the initial letter appearing in the sentence

I am currently exploring the possibility of altering the font color of the initial instance of a letter in a div. For example, if the String were 'The text' and I desired to make the color of 'e' yellow, then only the first e would be i ...

The variable 'form' has not been assigned an initial value in the constructor of the property

Below is the snippet from my component.ts file: import { Component, OnInit } from '@angular/core'; import { Validators, FormControl, FormGroup, FormBuilder } from '@angular/forms'; @Component({ selector: 'app-license', te ...

html inserting line break using label

I am attempting to dynamically set text to a label using jQuery. However, I am having trouble getting the <br> or \n to create new lines. Instead, all the text displays on the same line and wraps around. If you want to see my code in action, ch ...

Combine activities from a dynamic array of Observables

I'm currently utilizing the rxjs library. In my application, I have a Browser object overseeing multiple instances of Page objects. Each page emits a stream of events through an Observable<Event>. Pages can be opened and closed dynamically, le ...

Enhancing data binding in Angular 2.0 with string interpolation

In my script, I am working with a string that goes like this: {name} is my name. Greeting {sender} Is there a module available in Angular 2.0 that allows me to use something similar to the string.format() function in C#? I understand that it can be achie ...

Having trouble with Firebug throwing a '$(' error message?

I'm encountering a peculiar issue in Firebug that I'm not experiencing in Webkit. The error being displayed is '$(' in Firebug. Here is the code that seems to be causing this problem: $.getScript("http://kylehotchkiss.com/min/?g=packa ...

Only apply prevent default on specific levels for better control

I am currently working on a menu with submenus. I am facing an issue where when I click on a top-level menu item, I need to use prevent default because they are anchor tags. However, for the submenu items, I do not want to prevent default behavior. I am st ...