Dynamically updating the ng-class name in AngularJS

Exploring the integration of animate.css with AngularJS. Attempting to assign a class to an element on ng-click, but facing difficulties in updating the element. Various strategies were attempted, including modifying scope values through functions, without success. The goal is to add 'fadeIn', 'fadeOut', 'flipIn', and 'flipOut' classes to the animated element based on whether button 1 or button 2 is clicked.

<button ng-click="animate = !animate; classIn = 'fadeIn'; classOut = 'fadeOut'" class="btn btn-default">Fade</button>

<button ng-click="animate = !animate; classIn = 'flipIn'; classOut = 'flipOut'" class="btn btn-default">Flip</button>

<div class="animated-wrapper">
  <h1 class="text-center animated" ng-class="{'{{classIn}}': animate, '{{classOut}}': !animate}">Animation</h1>
</div>

Thanks

UPDATE: Experimentation with the code led to a solution (adjusting @hadiJZ's response slightly):

<button ng-click="setAnimateClass(animate = !animate, 'fadeIn', 'fadeOut')" class="btn btn-default">Fade</button>

<button ng-click="setAnimateClass(animate = !animate, 'bounceIn', 'bounceOut')" class="btn btn-default">Bounce</button>

<div class="animated-wrapper">
    <h1 class="text-center animated" ng-class="animateClass">Animation</h1>
</div>

And within the controller:

$scope.animate = true;

$scope.setAnimateClass = function (animate, classIn, classOut) {
  if (animate) {
    $scope.animateClass = classIn;
  } else {
    $scope.animateClass = classOut;
  }
};

Answer №1

Ensure the class name is enclosed in single quotation marks. Here is a simple example:

var myapp = angular.module('myapp', []);
myapp.controller('Ctrl', function ($scope) {
  var vm = this;
  vm.animate = true;
  vm.cssVal = "";
  
  vm.addFadeClass = function(animate){
    if(animate)
      vm.cssVal = "fadeIn";
    else
       vm.cssVal = "fadeOut";
    
    }
  vm.addFlipClass = function(animate){
    if(animate)
      vm.cssVal = "flipIn";
    else
       vm.cssVal = "flipOut";
    
    }
  
  
});
.fadeIn{
  color: red;
  }

.fadeOut{
  color:blue;
  }
.flipIn{
  font-size:20px;
  }

.flipOut{
  font-size:40px;
  }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="myapp" ng-controller="Ctrl as vm">
 <button ng-click="vm.addFadeClass((animate = !animate))" class="btn btn-default">Fade</button>
<button ng-click="vm.addFlipClass((animate = !animate))" class="btn btn-default">Flip</button>


<div class="animated-wrapper">
  <h1 class="text-center animated" ng-class="vm.cssVal" >Animation</h1>
</div>
  
</div>

Answer №2

Remove the duplicate curly braces and update as follows:

<h1 class="text-center animated" ng-class="{'classIn': animate, 'classOut': !animate}">Animation</h1>

Answer №3

Did you know that Angular allows you to use arrays as classes as well? Check out this link for more information: Read here

Simply create your array in the controller and bind it to ngClass.

ng-class="classArray"

$scope.classArray = [...]

Answer №4

Give this a shot:

<h2 class="center-content animated-text"
    ng-class="{fadeIn: animate, fadeOut: !animate}">Text Animation</h2>

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

developing a dropdown menu feature

I'm struggling with a small issue related to my drop-down menu function. My goal is to hide the visibility of a menu tab after it has been clicked for the second time. Below is the code snippet I've been working on: HTML:- <nav class="clea ...

Can you save data entered by a user into a text file using JavaScript or a similar technology in HTML, without the need to send it to a server?

Is there a way to create a site where user data is inputted into an input box or form, and then that information is stored in a .txt file on the user's C drive without uploading it to a server first? I've been experimenting with various forms an ...

Display a petite popup above the selected text within the Code Mirror editor

I have been utilizing the following code snippet to highlight text segments in Codemirror, a renowned code editor and syntax highlighter that can be downloaded from this link. Despite referring to the documentation, I am still unable to grasp how this fun ...

Is there a way to move the navbar to the right side of the screen?

How do I create a navigation menu that takes up half of the screen on the left side while allowing for scrolling on the right side without moving the navigation? What I am aiming for is similar to the images linked below: example example I attempted to u ...

Using HTML with Django Reportlab

Hey there! I'm currently experimenting with creating PDFs using Python Django and the reportlab library. While I've been successful in generating PDFs with simple text, I'm facing challenges incorporating HTML elements like <h1>Hello&l ...

AngularJS Error: Attempting to Access Undefined Object - Jasmine Testing

Encountering an error while running Jasmine tests when trying to mock/spy on an API call in the tests. Below is the code snippet responsible for calling the API: UploadedReleasesController.$inject = ['$log', '$scope', '$filter&apo ...

Steps for disabling a <select> <option> when a different item is selected in another <select><option> using Angular JS

I am working with two <select> <option> elements: <select name="fm" id="fm" class="form-control" > <option value="01" >All</option> <option value="01">01</option> <option value="02">02</optio ...

JavaScript function to substitute instead of writing

function replaceHTML(a,b) { var x = document.getElementById("canvas_html").contentDocument; x.innerHTML = b; } Although the current function works fine, I would like to update it to directly replace the existing content instead of writing new con ...

Adding Text Above a Material Icon in Angular: A Guide

Here is some sample HTML code to consider: <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/> <mat-icon class="fa fa-folder" style="font-size:48px;"><span style="color: re ...

An issue has occurred with the HTTP request to a PHP file in Angular

When attempting to send an http request to my php file, I encountered the following error message Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":" ...

How to extract the header of a current page using AngularJS

Is there a method in AngularJS to retrieve the header of the current page without making an additional API call? It doesn't appear to be documented, but it feels like it should be achievable. For example, if the Angular code is located in index.html, ...

Connect the front end files, including HTML, CSS, and JavaScript, to the Node.js backend

I'm a beginner in web development and recently completed an online course on node.js and express. However, the course didn't cover how to add HTML, CSS, and JS files when using Node. I attempted the following: var express = require('expres ...

Triggering a modal dialog in Mobile-Angular-ui through controller interaction

I have been encountering an issue with opening dialog from the controller while using mobile-angular-ui for mobile devices. controller $scope.openModal = function() { SharedState.initialize($scope, 'modal1'); // Share ...

Transferring temporary information from server to controller using angular-file-upload

Currently, I am utilizing the angular-file-upload library which can be found at this link: https://github.com/danialfarid/angular-file-upload. In the example provided on that page, data from a file is sent to the backend from a controller using the availab ...

Enhancing Form Spacing with Bootstrap

I have been working on a form design, but I am now facing alignment issues. The problem is more noticeable on larger screens compared to smaller ones. The main issues I am encountering include extra spacing in the social links section even though there ar ...

Looking for a pattern that combines Browserify and Angular?

Currently, I am embarking on a project using angular and browserify for the first time. I am seeking advice on how to properly utilize the require function with browserify. There are multiple ways to import files, but so far, I have experimented with the ...

"Encountering an Internal Server Error while trying to submit the

Seeking Assistance: I am experiencing an error when attempting to send a contact form. https://i.sstatic.net/7sK58.jpg The Visual Basic code causing the issue: <% mail_to = "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail=" ...

Update angular table input values

I am currently facing an issue with ng-table while displaying my data. I noticed that when I enter data on the first page and then navigate to the second page, the values from the first page get cleared. Is there a way to retain the previously entered val ...

uncovering the precise text match with the help of Beautifulsoup

I am looking to retrieve the precise matching value of text from HTML using Beautiful Soup. However, I am encountering some similar text along with my desired exact match. Here is my code: from bs4 import BeautifulSoup import urllib2enter code here url="h ...

Using jQuery to assign the value of a hidden element to data being posted

When using jQuery's post() method to call an ajax action that returns JSON data ({"Success": "true" } or {"Success": "false"}), the value of a hidden HTML element is supposed to be set to the Success value in the returned object. However, after settin ...