Adding a class to an element in AngularJS

I have a question about entering empty values in an input field and highlighting its boundary. I added a new class 'warning' for this purpose and created the following code.

HTML:

`<body ng-app="TestPage">
 <form ng-controller="TestForm">
  <input ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
  <button ng-click="submitButton()">Click</button>
</form>
</body>`

JavaScript:

`angular.module('TestPage',[])
    .controller('TestForm', function($scope, $animate) {
         $scope.submitButton = function() {
             if (($scope.testinput == undefined) || ($scope.testinput == "")) {
                 $animate.addClass($scope.testclass, "warning");
             }
         };
    });`

However, the addClass function does not seem to work as expected. What could be the issue here?

Answer №1

Per the documentation

The $animate service's addClass function requires three parameters:

The first parameter is the element to which the CSS classes will be applied.

The second parameter is the CSS class(es) that will be added (multiple classes separated by spaces).

The third parameter is an optional collection of options/styles to apply to the element.

To implement this, you can follow this example:

html:

`<body ng-app="TestPage">
 <form ng-controller="TestForm">
  <input id="target_element" ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
  <button ng-click="submitButton()">Click</button>
</form>
</body>`

Javascript:

`angular.module('TestPage',[])
    .controller('TestForm', function($scope, $animate){
        $scope.submitButton = function(){
            if (($scope.testinput == undefined) || ($scope.testinput == "")){
                $animate.addClass(angular.element('#target_element'), "warning");
            }
        };
    });`    

A more effective approach is to use the directive.

module.directive('addClassBy',['$animate',function($animate){
    return function(scope,element){
        scope.$watch('testinput',function(newValue,oldValue){
            if(newValue === oldValue){return};
            if(newValue === undefined || newValue === ''){
                 $animate.addClass(element,'warning')
            }
        })
    }
}])

Then in HTML:

`<body ng-app="TestPage">
     <form ng-controller="TestForm">
      <input add-class-by ng-model="testinput" class="form-input" ng-class="testclass" type="text"/>
      <button ng-click="submitButton()">Click</button>
    </form>
    </body>`

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

Retrieving users by their Id's from MySql database using NodeJS

Goal: I aim to gather a list of users from a table based on the currently logged-in user. I have successfully stored all user IDs in an array and now wish to query those users to display a new list on the front end. Progress Made: I have imported necessa ...

JavaScript refuses to execute

I am facing an issue with a static page that I am using. The page consists of HTML, CSS, and JavaScript files. I came across this design on a website (http://codepen.io/eode9/pen/wyaDr) and decided to replicate it by merging the files into one HTML page. H ...

Issue with getStaticProps in Next.js component not functioning as expected

I have a component that I imported and used on a page, but I'm encountering the error - TypeError: Cannot read property 'labels' of undefined. The issue seems to be with how I pass the data and options to ChartCard because they are underline ...

Ways to transfer information from the Component to the parent in AngularJS 1.x

I am facing an issue with my component that consists of two tabs containing input fields. I need to retrieve the values from these input fields when the SAVE button is clicked and save them to the server. The problem lies in the fact that the SAVE function ...

Host an Angular app with views using Express.js - reloading is disabled

I'm currently working with an expressjs configuration that looks like this: app.use(express.static(path.join(__dirname,"../../site"))); app.use("/src", express.static(path.join(__dirname,"../cms/src"))); app.get('/', function(req, res){ ...

An issue encountered with res.download() following res.render() in Node.js

Just started working with Node JS and ran into an issue: Error: Can't set headers after they are sent. I've checked my code, and the problem seems to be related to res.download(); Is there a way to display the view without using res.render()? ...

I am looking to create buttons that can switch between two different styles of a specific element, like an h1 tag, when clicked. However, instead of toggling

//In this HTML document, I am trying to achieve a functionality where my buttons can toggle the style of an h1 element between the colors yellow and purple when clicked. However, I have encountered an issue where the buttons disappear during a transition ...

Verify whether the labels are blank, remain as they are, or transfer the data to the database

Currently, I am utilizing PHP, HTML5, and JavaScript for my project. The task at hand involves creating a webpage that will be connected to a database. However, I have encountered an issue wherein the page proceeds to the next step and sends data even when ...

What steps should I take to have a button initiate an AJAX request?

One of the tasks on my list involves a textbox and a button for interaction. Once text is entered into the textbox, I intend to trigger an AJAX request by clicking the button. The purpose of this AJAX call is to extract the text input and incorporate it i ...

Auto-scroll feature malfunctioning

My auto scroll function using jQuery isn't working, here is my CSS: #convo_mes{ text-align:left; width:98%; height:80%; background:#fff; border:1px solid #000; overflow-x:auto; } And in my JavaScript: $(".mes").click(functio ...

Effortlessly submit form data in Codeigniter without the need for page refreshing using jQuery ajax

I've been working on submitting form data in the codeigniter framework using ajax and jQuery to prevent page refreshing, but I keep getting a fail message. Since I'm new to ajax, can someone help me troubleshoot this error? This is my Controlle ...

What is the best way to handle constants in TypeScript?

I am facing an issue with a React component I have created: const myComponent = ({constant}: Iprops) => ( <div> {CONSTANTS[constant].property ? <showThis /> : null </div> ) The error message says 'element implicitly has ...

Changing the image source dynamically at runtime using JavaScript and jQuery

Is it possible to dynamically change the source of an image using jQuery during runtime? I have set up a jsfiddle to demonstrate my question. I am attempting to load the image specified in the variable $newsrc when a button is clicked. However, I am unsure ...

Chakra UI: How come the tooltip is appearing in the top left corner of the screen instead of directly above the element?

CreatedByModal is a unique chakra modal that incorporates tooltips. However, I am facing an issue where the tooltip appears at the top of the screen instead of directly above the icon when hovering over the icons. You can see in the image provided that the ...

There is no need for blank space when using the JSF inputtext component

When using a jsf form with required inputs, checking for empty spaces can be important. Utilizing the required="true" attribute helps, but it's also necessary to prevent users from submitting forms with just empty space characters entered. One approac ...

Tips for verifying that a file has not been selected in Croppie

Whenever I use croppie to crop images on my website, everything works fine when I select an image and upload it. But if I try to crop and upload without selecting an image, a black image gets uploaded instead. How can I validate if the file upload is empty ...

What exactly does the statement if(item.some((item) => !item.available) represent in typescript?

Can you explain the meaning of if(item.some((item) => !item.available))? While looking at some code randomly, I came across this snippet: if(item.some((item) => !item.available){ } I'm curious about what it signifies. Can you elaborate on it? ...

Display a list of errors from an array in JavaScript or jQuery, and output them into a designated <

I need assistance with displaying a list of error messages in a specific div. Within my code, I have a #error-list div and an array called errors that contains various error messages: var errors = ["First name is blank", "Last name is blank", "Company na ...

What is the process of using JavaScript code to read a text file?

Trying to use Google Charts while reading data from a text file. The code in JS is written for this purpose: function readTextFile(file){ var rawFile = new XMLHttpRequest(); rawFile.open("GET", file, false); // using synchronous call var allTe ...

Node.js: Extract the object's name and value that are sent from the frontend

I'm in the process of creating a microservice using nodejs. The request is returning the following JSON. { "distCd": "abcd", "distName": "parentLife Distributor (TOD)", "stateCd": "", "subdistInd": false, "maindistInd": true ...