Set the class of an element dynamically using ng-class and detect changes with ng-change

I want the input field to initially have the class .form-control-error. When the user clicks on the field and starts typing, I would like it to change to .form-control-success.

I attempted the following code but couldn't get it to update. The ng-change is working as expected, so it seems to be an issue with updating the css.

CSS:

// ... more classes
.form-control-error:focus {
    border-color: #FF0000;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}  
.form-control-success:focus {
    border-color: #5cb85c;
    box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 8px rgba(255, 0, 0, 0.6);
}

JS:

$scope.changeEmail = function () {
    console.log('change');

    $scope.formControlColor = function () {
        return 'form-control-success';
    };
};

HTML:

<input type="text" id="email" ng-model="email" ng-change="changeEmail()" placeholder="email" ng-class="{'form-control-error': !formControlColor()}" class="form-control input-lg margin-bottom-15">

Answer №1

formControlColor is a function that will provide the necessary class. If you wish to use this return value in ng-class, simply call the function.

<input ... ng-class="formControlColor()" ... />

To ensure the function has an initial definition and displays the correct class when the page loads, your JavaScript code should be similar to:

$scope.formControlColor = function(){
    return 'form-control-error';
};
$scope.changeEmail = function () {
    console.log('change');

    $scope.formControlColor = function () {
        return 'form-control-success';
    };
};

If the value remains constant and doesn't require any complex computation, you can eliminate the function and directly use a string instead. In that case, it would look like:

HTML

<input ... ng-class="formControlClass" ... />

JavaScript

$scope.formControlClass = 'form-control-error';

$scope.changeEmail = function() {
    $scope.formControlClass = 'form-control-success';
}

Answer №2

To set the return value as the setter and include the options in the ng-class object, you can use the following approach. If formControlColor evaluates to false, it will display an error CSS; otherwise, it will show a success CSS:

    <input type="text" id="email" ng-model="email" ng-change="changeEmail()" placeholder="email" 
ng-class="{'form-control-error': !formControlColor, 'form-control-success': formControlColor}" class="form-control input-lg margin-bottom-15">

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 loopback: Record cannot be inserted into associated model using lbServices functions

I am currently in the process of developing an application that utilizes Loopback as the backend, AngularJS as the frontend, and MySQL as the database. The versions being used are Loopback 2.22.0 and Loopback Angular SDK 1.5.0. Within the application, the ...

How to make Sails.js package accessible across all modules

Recently, I have been using Sails frequently and came across a common practice question. Whenever I need to use a specific NPM package multiple times in a project, I typically include it in my config/bootstrap.js file like this: module.exports.bootstrap = ...

What steps can I take to modify my webpage, like a dashboard, on the internet?

Whenever I click on a menu item in the sidebar of my HTML file, I want only the body section to change without affecting the navigation or sidebar content. For instance, if I select the "Coding Convention" menu in the sidebar, I would like the page to swi ...

Can the color of text be adjusted (to either white or black) based on the background color (in any color and format)?

To achieve a text color that contrasts well with any background, I need to make sure it's either black or white. The background in my app can vary in color and format, so finding the perfect solution has been challenging. Using mix-blend-mode doesn&a ...

Understanding intricate JSON structures with JavaScript

Here is the JSON structure that I am working with: var data = [ { "country":"Andorra", "code":"AD", "state":[ { "state_code":"AD1", "state_description":"aaAndorra1" }, { " ...

The Cordova minification tool fails to compress files within the browser platform

I recently installed the cordova-minify plugin to compress the javascript code in my Cordova app. When I tried running the command: cordova build browser An output message appears: cordova-minify STARTING - minifying your js, css, html, and images. ...

How to populate an ExtJS 3.4 combobox with local JSON data in a few simple steps

I am utilizing ExtJS 3.4 and in need of populating a combobox with specific data obtained from a previous XMLHttpRequest, stored in a variable as follows: my_variable = "[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","no ...

In react-native, both the parent and child components are rendered at the same time

One of my components, the parent one, goes through an array of chapters and for each item found, renders a child component called 'ExercisesList' and passes an array of exercises to it. class ExercisesScreen extends Component { displaySelected ...

When using the .append method in jQuery, the JSON array only displays the last value of the array when iterating through it with

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Displaying Array Data in Table Using Javascript</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">& ...

Show the total of a JavaScript calculation in a designated input box

Is there a way to show the total sum of this calculation in an input field? function calculateSum1() { var sum = 0; //loop through each textbox and add their values $("input.miles").each(function() { //only add if the value is a number ...

Is it possible to display a "click" message when a button is hovered over using CSS?

Whenever I hover over a button, I struggle to receive the appropriate message like "click" or "enter" before actually clicking it. How can I use CSS to style my buttons in a way that allows for this pre-click messaging? I have tried approaches such as .bu ...

Is it possible to save data to a file using React?

As I work on a React web application, the need has arisen to store crucial user data on the client side in a stable manner. Due to the requirement of data stability and the constraint against using Indexed DB, I am considering storing the data as JSON in ...

Mastering the art of redirection in Node.js

Encountering an issue with redirecting between directories - having trouble directing to another file in a different directory. Here is my directory structure: -views -add_user.jade -routes -index.js Attempting to redirect to add_user.jade from inde ...

Connect to content on the current page

I am facing an issue where the linked heading of a section on the same page is getting lost under the fixed navigation bar when scrolling down. This problem seems to only occur on desktop view as it works fine on mobile preview. Here is the code I am curre ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Issue encountered while attempting to load several google charts simultaneously

What do I need? I am in need of two Google charts, one on each tab of the website as shown in the screenshot below: Tabs What seems to be the issue? The second chart is not loading properly and showing mixed information. This can be observed in the scre ...

The context of the selector causes an error to be thrown

Why does jQuery throw an exception when I attempt to select an element with context? The code is as follows: jQuery('b', "DAS<br/><br/><b>ID</b> = 02<br/><b>NAMA DAS</b> = CITARUM<br/><b>LUAS ...

Is it possible to instantiate a Backbone view by referencing its string name that is stored within a JavaScript object?

I am currently working on a visual builder that utilizes different views for each component. Each view is defined as shown below: $(function() { var parallaxView = new Backbone.view.extend({ .... }); var parallaxView = new Backbone.view.e ...

"Utilizing jQuery's bind method with IE 7 compatibility and the use of

One of the scripts I'm working with is a treeview script, and a portion of it appears like this: root.find("." + classControl).each(function () { $(this).bind('click', function () { if ($(this).text() == "-") { $(thi ...

Tips for customizing the appearance of date circles and text in Vue V-Calendar.io

On v-calendar.io, there is a demo showcasing the correct display where the date "2018-01-01" has a red background and dark text: However, my display does not match that. I have included Vue.js and v-calendar through CDN, and the page is formatted in HTML ...