Ways to automatically update ng-class based on changes in ng-model value

I am working on a code where I need to add classes to the 'label' based on whether the input box is empty or not. To achieve this, I am checking if the input box is null and adding classes accordingly.

<div class="col-md-12">
    <input type="text" name="name" id="name" class="input-border" ng-model="userProfile.name"/> {{userProfile.name}}
    <label for="name" ng-class="userProfile.name === null ?'custom-label-no-content':'custom-label-content'" class="xs-keep-label-in-place">Display Name</label>
  </div>

Answer №1

Check out this answer that doesn't require a controller,

When working with a text box, consider using

userProfile.name.length and !userProfile.name.length

ng-class="{ 'custom-label-no-content': userProfile.name.length, 'custom-label-content': !userProfile.name.length }"

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
<style>
.custom-label-no-content {
    color:white;
    background-color:lightblue;
    padding:20px;
    font-family:"Courier New";
}
.custom-label-content {
    background-color:coral;
    padding:40px;
    font-family:Verdana;
}
</style>
<body ng-app="">
<div class="col-md-12">
<input type="text" name="name" id="name" class="input-border" ng-model="userProfile.name"/> {{userProfile.name}}
  <label for="name" ng-class="{ 'custom-label-no-content': userProfile.name.length, 'custom-label-content': !userProfile.name.length }" class="xs-keep-label-in-place">Display Name</label>
  </div>
  

</body>
</html>

Please test the code snippet above

View the live demo here

Answer №2

There are several ways to achieve this.

1. Implementing a Function in the Controller (recommended)

html

<label for="name" ng-class="labelClass()" class="xs-keep-label-in-place">Display Name</label>

JS

$scope.labelClass = function(){
    var classes = [];
    if($scope.userProfile.name === null){
        classes.push('custom-label-no-content');
    }else{
        classes.push('custom-label-content');
    }
    return classes;
}

2. Using an Expression with single curly brace

html

<label for="name" ng-class="{ 'custom-label-no-content': userProfile.name === null, 'custom-label-content': userProfile.name !== null }" class="xs-keep-label-in-place">Display Name</label>

3. Applying a Switch Statement with hardcoded class

html

<div class="col-md-12" ng-switch="userProfile.name === null">
    <input type="text" name="name" id="name" class="input-border" ng-model="userProfile.name"/> {{userProfile.name}}
    <label for="name" ng-switch-when="true" class="custom-label-no-content xs-keep-label-in-place">Display Name</label>
    <label for="name" ng-switch-when="false" class="custom-label-content xs-keep-label-in-place">Display Name</label>
</div>

I personally recommend option 1 as it adheres to the MVC pattern, keeping logic in the controller and view code focused on display purposes.

Answer №3

Here is a suggestion to try out.

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
    <style>
        .custom-label-no-content {
            border: 1px solid red;
        }
        .custom-label-content {
            border: 1px solid green;
        }
    </style>
<body>

    <div ng-app="myApp" ng-controller="myCtrl">

        <input type="text" name="name" id="name" class="input-border" ng-model="userProfile.name" /> {{userProfile.name}}
        <label for="name" ng-class="userProfile.name === '' ?'custom-label-no-content':'custom-label-content'" class="xs-keep-label-in-place">Display Name</label>
    </div>

    <script>
        var app = angular.module('myApp', []);
        app.controller('myCtrl', function ($scope) {
            $scope.userProfile = {};
            $scope.userProfile.name = '';
            
        });
    </script>


</body>

</html>

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

What is the origin of this mysterious error?

I'm working on a function to format various types of variables and utilize a toString() method. It's handling complex objects, arrays, and circular references flawlessly. However, when testing it on a jQuery object using format($("body")) with l ...

Using the Tailwind CSS framework in combination with Vue's v-html

My vue component is designed to accept a prop of raw HTML, which originates from a wysiwyg editor utilizing tailwind classes for styling - similar to our vue app. The issue arises when using v-html="responseFromAPI" in my component, as the raw H ...

Changing the CSS class of the Bootstrap datetime picker when selecting the year

Is there a way to change the CSS style of the Bootstrap datetime picker control so that when selecting years, the color changes from blue to red? I attempted to do this with the following code: .selectYear { background-color:red!important; } However ...

When attempting to execute a function within another function in JavaScript, a ReferenceError is triggered

I recently developed a straightforward app that utilizes the Google Drawing Library (https://developers.google.com/maps/documentation/javascript/examples/drawing-tools) to allow users to draw circles on a map. The first circle represents the source locatio ...

The `XMLHttpRequest.prototype.open` function does not capture every single HTTP request visible in the chrome-dev-tools

While utilizing a third-party embedded code that initiates HTTP requests with a request header origin different from my own, I encountered an issue. Despite attempting to intercept these HTTP requests using XMLHttpRequest, they do not get intercepted. This ...

Extract data from a CSV table stored in a variable using node.js

Currently, I am working on a node application that can potentially result in a CSV formatted table being stored in a variable. I am interested in converting this CSV data into a JSON format. I have explored various modules, but it appears that most of th ...

Leveraging jQuery or javascript to display json data in a table with multiple columns

My goal is to convert a JSON data into an HTML table that dynamically creates columns based on the content of the JSON. However, I am facing challenges in looping through the JSON and rendering multiple columns when necessary. The desired output for the e ...

Transforming the inputted URL into a clickable hyperlink

I have a text input field where any text entered is displayed below using angular.js. However, I am trying to convert any http URL entered into a clickable link. I found reference to the solution on this Stack Overflow page. Despite successfully converting ...

React-Native Error: Invalid element type detected

While attempting to run my React Native app on my iPhone using Expo, I encountered an error displayed in a red background area. Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite ...

Creating a form that can identify both letters and numbers using JavaScript

Is it possible to create an <input> field that can recognize both letters and numbers while disregarding spaces and capitalization? Here is my current progress, aiming for the feedback to display as "right" when 9 H 6 U 8 f is entered in the field, ...

How can I retrieve a list from an Angular object using Java Rest services?

For my code generation, I rely on Jhipster. In my project, there is a class called Calendar which contains a list of Events. I am trying to access this events list in my Angular controller/view. Although I can retrieve the Calendar object using a Java Res ...

The React.js project I created is showcased on GitHub pages and has a sleek black design

After developing a project using React.js and deploying it on github pages, everything was functioning smoothly. However, I encountered an issue where the screen turned black after logging in and out multiple times. Are there any suggestions on how to reso ...

Ways of accessing an array within an if statement

I have a dashboard with admin privileges for my application. In this dashboard, the admin can select a user from a dropdown list. Once a user is selected, I make an AJAX call to retrieve the user's data and store it in a variable named $result. Howeve ...

The parameters used in the json.parse function in javascript may be difficult to interpret

Currently, I am examining a JavaScript file on this website. It contains the following code: let source = fs.readFileSync("contracts.json"); let contracts = JSON.parse(source)["contracts"]; I'm curious about what exactly the JSON.parse function is d ...

Leveraging the node CLI tool as a library for trimming MP3 files (trimp3

I recently came across a fantastic library that I am interested in using for my nodejs project: https://github.com/kyr0/trimp3 The only issue is that it functions as a cli tool, and I would like to integrate it seamlessly into my codebase as a library. D ...

Avoid using the JQuery IIFE outside of the document ready function as it is considered a

Hey there! I've been coming across a puzzling "pattern" lately that doesn't sit well with me. The code seems messy and lacks clear structure. I've included a sample of the code for context. Is declaring all those IIFEs outside the document ...

Are 'const' and 'let' interchangeable in Typescript?

Exploring AngularJS 2 and Typescript led me to create something using these technologies as a way to grasp the basics of Typescript. Through various sources, I delved into modules, Typescript concepts, with one particularly interesting topic discussing the ...

There is a button on my website that uses a small piece of Javascript to post a tweet, but unfortunately, it is not functional on mobile devices

Check out this link to view the demonstration - http://codepen.io/illpill/pen/VbeVEq function sendTweet(message, author) { window.open('https://twitter.com/intent/tweet?hashtags=thequotemachine&text=' + encodeURIComponent('"' + m ...

Preventing duplicate text fields from being added to an array in Angular JS - a step by step guide

When a user tries to create a new text box, I want to prevent it and display an error message if they enter the same value in the previous text field. Therefore, proceed with creating a new text box only if the values are different. HTML <input type=" ...

Encountering difficulties linking to a stylesheet or a script in an HTML file delivered by Express server

Currently, I'm facing the challenge of breaking down my Express app code into multiple files. Unfortunately, I am unable to utilize <link href> or <script src> for linking stylesheets or scripts. Below is the relevant snippet from my inde ...