What are some creative ways to animate Angular ng-switch for both entering and leaving transitions?

I have created an angular directive named 'cardViewer' that is designed to display images with animation. The directive enables the user to slide the image to the left when pressing the "prev" button and to the right when pressing the "next" button.

Initially, I attempted to accomplish this using the ng-switch directive, which only supports the .ng-enter and .ng-leave animation classes. However, I needed two ways to enter (from left and right) and two ways to leave (to left and right).

To address this issue, I implemented the ng-class approach in hopes of adding the toLeft class before the switch to apply a specific CSS animation. Unfortunately, it did not work as expected. When I pressed the "next" button twice, it functioned correctly; however, if I pressed "next," followed by "prev," the new image entered from the right direction while the old image left in the wrong direction.

The template structure of my directive consists:

<h1>hahaha</h1>
  <div>
    <button ng-click='prev()'>prev</button>
    <button ng-click='next()'>next</button>
  </div>
<div>current Card Index: {{displayCard}}</div>

<div class="card-container" ng-switch="displayCard">
...images with corresponding switch cases...
</div>

In the directive script:

angular.module('app', ['ngAnimate'])
  .directive('cardViewer', function() {
  // directive implementation
});

The applicable CSS styles are then defined including animations for entering and leaving the cards in different directions.

You can explore the full code sample on my Plunker page here: cardViewer

If you have any insights on what might be causing the incorrect behavior in my code or suggestions on how to achieve multiple ways of entering/leaving with ng-switch, please share your thoughts.

Answer №1

The issue arises because ngSwitch invalidates the scope of the current image prior to allowing ngClass to trigger and switch the class of that image from toRight to toLeft (or vice versa) before the animation commences.

ngSwitch generates a fresh scope and runs at priority level 1200, while ngClass operates at priority level 0.

To resolve this, simply update your next and prev methods so they adjust the displayCard attribute within a $timeout, after setting toLeft and toRight, enabling ngClass to act on the updated toLeft/toRight settings before ngSwitch erases that scope.

For instance, your next method should be modified as follows:

scope.next = function() {
  scope.toLeft = false;
  scope.toRight = true;

  // This needs to be done within a $timeout so that ngClass can
  // update the class of the current image based on the new 
  // toLeft and toRight values before ngSwitch modifies the
  // displayCard property and destroys the current image's scope.
  $timeout(function () {
    if (scope.displayCard == 3) {
      scope.displayCard = 1
    } else {
      scope.displayCard += 1;
    }
  }, 0);
};

Here is an edited version of your plunk demonstrating the solution in action. Check the console for log messages indicating when ngClass applies the classes and ngSwitch creates/destroys scopes.

I have retained your original "next" and "prev" buttons while adding "next (fixed)" and "prev (fixed)" buttons so you can observe the differences in log messages: how ngSwitch dismantles the scope before ngClass takes effect with the original buttons, versus ngClass executing before ngSwitch disrupts the scope with the fixed versions.

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

Ways to Deduct 10 Days from a Date using JavaScript

After receiving some helpful suggestions, I managed to solve my date issue by using moment.js. Here is the snippet of code where I implemented moment.js: var preorderdate = moment(date).subtract('days',10).format('MMMM D, YYYY'); var r ...

Having trouble establishing a connection to MySQL through NodeJS and Express

I am currently attempting to establish a connection to MySQL using a nodeJS app with express as the server. I have referred to the mysql npm documentation to start the connection process, but I keep encountering an error in the callback function within cre ...

Is it possible to send both the authRequired and WL.Server.invokeHttp values back to the client side using web services in Adapter-based authentication with Worklight?

When using Adapter based authentication with worklight and angularJs, the submitLogin procedure is called upon clicking the login button to pass the username and password as parameters. The query arises after invoking the adapter on how to return both the ...

Node.js is a powerful platform that allows developers to efficiently manage PostgeSQL connection

My application successfully connects to the database using the connection pool method, allowing for smooth data insertion. However, I am experiencing slowdowns with other queries in the same file. I have attempted to use the release() method without succe ...

Managing cookies in PHP and JavaScript can present challenges due to variations in how different browsers

Our website utilizes ExpressionEngine as the CMS and Magento's cart for e-commerce. I am encountering challenges with cookies and their accessibility in various sections. A cookie is used for storing search selections, allowing users to return to our ...

The window.focus() function does not seem to be functioning as expected when using

I have been trying to use this code snippet to bring the window into focus. It seems to be working smoothly on Internet Explorer, but unfortunately it is not behaving as expected in Firefox. Any tips or recommendations would be greatly welcomed. ((Javas ...

Is my approach correct in utilizing hierarchical data structure for geospatial/geohash searching in firebase?

Objective: Develop a database of aerial photography. Data should be entered using AngularJS forms and retrieved using a map viewer like leaflet. Aims: Retrieve information in various ways: by Flight, Collection, Image by ID, and Image by Geography Da ...

Please ensure to refresh the page after confirming the alert box by clicking OK

Is it possible to clear certain inputs on my Magento store's checkout page when an alert box is displayed and the user clicks OK? Unfortunately, I do not have control over the JavaScript alert. Therefore, I thought of implementing a script that can d ...

Utilizing Angular Forms for dynamic string validation with the *ngIf directive

I have a challenge where I need to hide forms in a list if they are empty. These forms contain string values. I attempted to use *ngIf but unfortunately, it did not work as expected and empty fields are still visible in the list. How can I address this iss ...

How come my strategies for React function components aren't producing results?

Currently, I am working on a project that involves utilizing the Moviedb API. In this project, I have developed a Movie component to display a list of movies and handle API requests. From the Movie component, I pass on the movie's release date and gen ...

npm scripts using nodemon to monitor changes in js and scss files

Currently, I am exploring the process of setting up a development environment using NPM exclusively, without relying on grunt.js or bower.js. To guide me through this setup, I referred to a tutorial available at In order to monitor my .js and .scss files ...

What could be causing BeautifulSoup to overlook certain elements on the page?

For practice, I am in the process of developing an Instagram web scraper. To handle dynamic webpages, I have opted to utilize Selenium. The webpage is loaded using: driver.execute_script("return document.documentElement.outerHTML") (Using this javascript ...

Enhancing the appearance of an Angular.js application

On the same page, there are two buttons - one for buying and one for selling. It appears that both buttons share the same HTML instance. This creates a problem when trying to style them individually using classes, ids, or other HTML-targeted selectors, as ...

Ways to permit https://* within a content security policy (CSP) configuration

I'm currently incorporating CSP into my website but encountering an issue with the img-src header. I'm using NodeJS and Express to develop the site for my Discord Bot, and I want to revamp it but I've hit a roadblock. ====== This is the co ...

Encountering TypeError while attempting to assign an axios response to a data variable within a Vue component

Encountering the error message TypeError: Cannot set property 'randomWord' of undefined specifically at the line: this.randomWord = response.data.word; Confirming that console.log(response.data.word) does display a string. Vue Component Structu ...

The document does not contain any serialized JavaScript files

Hey there, I'm facing an issue with my Codeigniter and JavaScript file upload and insertion into the database. I'm not getting any response, so could you please take a look at my code and share some valuable ideas? Below are the codes for the vie ...

Error: The function of splitting 'a' is not available within the context of 'r' (angular.js:263

Although I comprehend the error message, I have not implemented any split functions in my application. The error seems to be originating from the angular.js file itself and is something that has only surfaced recently. I am curious to know if anyone else i ...

Passport.socket.io cannot resolve the issue of a missing session

The Issue I am facing a problem with the failed connection to socket.io: No session found using passport.socketio.js and I am unable to identify the root cause. Despite checking similar posts, the configuration seems fine to me. However, it appears that ...

Is there a way to execute the identical promise once more based on the outcome of the previous execution?

My dilemma involves a block of code enclosed within a promise. This particular code is responsible for modifying records in a remote database and reporting the number of records edited. In case the count of edited records exceeds 0 (indicating work done), ...

Django: Automatically redirecting if the URL was manually entered by the user

Is there a way to prevent users from manually entering a URL of a specific page? For instance, let's assume I have two pages - somepage.com/home and someplace.com/other. On the home page, there is a button that directs users to the /other site. I wan ...