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

Shades of Grey in Visual Studio Code

Whenever I use VSC, I notice these odd grey boxes that appear in my editor. They seem to be dynamic and really bother me. Interestingly, switching to a light theme makes them disappear. However, I prefer using a dark theme and haven't been able to fin ...

Is it possible for me to include a static HTML/Javascript/jQuery file in WordPress?

My extensive HTML file contains Javascript, jQuery, c3.js, style.css, and normalize.css. I am wondering if I can include this file as a static HTML page within Wordpress. Say, for instance, the file is called calculator.html, and I want it to be accessib ...

Ajax continues to operate even if an error is detected

Hello fellow programmers! I'm currently facing an issue with form submission and validation using jQuery with 2 ajax events. The problem lies in the fact that even if the first ajax event (timeconflict.php) returns an error, the second ajax event (res ...

bootstrap thumbnail displayed without a border

I have decided to incorporate Bootstrap into my latest project: <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS ...

What is the best way to determine which CSS class is shown when the page is loaded using JQuery?

I am facing a dilemma with displaying my site logo. I have both an image version and a text version, and I want to choose which one to display based on the vertical position on the page and the screen width. <a class="navbar-brand" id="top-logo" href=" ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

What is the best way to display the output after retrieving an array?

Database : --> product table P_id P_name P_uploadKey 1 Cemera 7365 2 Notebook 7222 3 Monitor 7355 4 Printer 7242 --> buy table B_id P_id B_nam ...

Tips for passing a parameter to the $routeProvider

I am currently using AngularJS for my App project. Can someone please guide me on how to pass the parameter callbackUrl after '?' to the $routeProvider? The desired output url format should be: '/admin/test/profile/123456/edit?callbackUrl= ...

Position two div elements evenly with text enclosed in a container

I'm looking to incorporate two distinct blocks of text into a container https://i.stack.imgur.com/6mFZK.png Criteria: Text 1: positioned at the top left corner (85% of box size) Text 2: positioned at the bottom right corner (15% of box size) I&ap ...

Issues arise when trying to use JQuery in conjunction with JSON data

I've been working on a project that involves creating a dynamic dropdown list, but I've run into an issue with jQuery and JSON. This is my first time working with JSON, so I'm still getting the hang of it. Despite googling for solutions, I h ...

How to use image blob in Angular JS?

Working with API endpoints that require authentication for image retrieval. Utilizing a service called authenticatedHttp as an abstraction over $http to manage authentication tokens successfully. Successfully receiving response, converting blob to object ...

What could be causing my Chrome extension's AJAX calls to behave synchronously?

Recently, I've been experimenting with implementing AJAX in a Chrome extension. Within my content script, the goal is to inject some HTML into an existing page. I've attempted using JQuery.get, JQuery.load, and ng-include. To my surprise, all ...

Enhance the appearance of the popover by incorporating an arrow-like element for dismissing the

Here is some code I want to modify: https://i.stack.imgur.com/0C61Y.png I would like to add an arrow element at the top, similar to this: https://i.stack.imgur.com/pDT3s.png This will give it a popup-like appearance. Below is the CSS styling for the co ...

Can you explain the distinction between $scope.$root and $rootScope?

When looking at controllers, I noticed that $scope includes $root. Can you explain what $root is and how it differs from the $rootScope that can be injected into the controller? ...

Angular Modal Service Unit Test Template for $uibModal

My service has a simple show() function that basically calls $uibModal with some configuration and returns the modal instance function customModalService($uibModal) { return { show(message) { return $uibModal.open({ bindToController: t ...

Redirect the Submit button to the specified URL from the form element

Looking for a way to create a form with two fields: Username and Password. Upon clicking submit, the username and password should be added to the URL in a specific format. For instance: The URL structure will remain the same, only the "username_entered_i ...

When using $http post in Angular, I encountered an issue with an unhandled rejection error

After successfully setting up my $http post request in Angular, I encountered an issue when refreshing the page. The console displays the following error: Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"POST","transformRequest": ...

Establishing connections between HTML and CSS files

After writing my html and css code, I noticed that the files are not linking properly. Despite checking for errors, I couldn't find any issues within the codes. Here is a snippet of my html file: <!DOCTYPE html> <html lang="en" dir= ...

Navigate to the specific page using the router-link with the designated path

I have 10 different filters displayed in a table and I want each filter name to link to a specific page. Here is an example of my table row: <md-table-row v-for="(row, index) in manage" :key="index"> In the first cell of the table, I'm trying ...

Is there a way to modify the appearance of a text box to suit individual preferences?

Is it possible to alter the shape of a text box, creating a rectangle with a portion removed from one side? I have included an example image for reference. I came across clip-path: polygon in CSS, but it seems to only accept four coordinates. Thank you i ...