Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method without relying on javascript.

Question: Is it feasible to utilize angular's ng-enter and ng-leave css transitions while specifying a callback for when the animation finishes? Since the animationend event fires, there must be a way to accomplish this.

This is what I currently have:

HTML:

<div ng-if="item" class="myDiv"> {{ item.name }} </div>

CSS:

.myDiv.ng-enter {...}
.myDiv.ng-enter.ng-enter-active {...}
.myDiv.ng-leave {...}
.myDiv.ng-leave.ng-leave-active {...}

My objective is to invoke myDone() once the animation completes (i.e., after the removal of the ng-enter-active class).

Answer №1

Absolutely, you have the ability to achieve this using the $animate service. Typically, this would be implemented within a custom directive. An example of a simple animation scenario would be triggering an element's animation on click. For instance, removing an element with a specified animation using .ng-leave and passing a callback.

app.directive('leaveOnClick', function($animate) {
  return {
    scope: {
      'leaveOnClick': '&'
    },
    link: function (scope, element) {
      scope.leaveOnClick = scope.leaveOnClick || (function() {});
      element.on('click', function() {
        scope.$apply(function() {
          $animate.leave(element, scope.leaveOnClick);
        });
      });
    }
  };
});

This directive could be utilized as follows:

<div class="my-div" leaveOnClick="done()">Click to remove</div>

To fade out the element via CSS, you can use the following styles:

.my-div.ng-leave {
  opacity: 1;
  transition: opacity 1s;
  -webkit-transition: opacity 1s;
}
.my-div.ng-leave.ng-leave-active {
  opacity: 0;
}

You can view the above animation in action on this Plunker.

However, ngIf does not offer any built-in callbacks to work with that I am aware of. Therefore, you would need to create your own directive. Below is a reference to a modified version of ngIf, originally sourced from the ngIf source code, which has been renamed to animatedIf. Usage example:

<div class="my-div" animated-if="shown" animated-if-leave-callback="leaveDone()" animated-if-enter-callback="enterDone()" >Some content</div>

The key difference here is the addition of a 'scope' parameter to pass in the necessary callbacks:

scope: {
  'animatedIf': '=',
  'animatedIfEnterCallback': '&',
  'animatedIfLeaveCallback': '&'
},

Additionally, the calls to $animate.enter and $animate.leave have been adjusted to call these callbacks after animations:

var callback = !oldValue && $scope.animatedIfEnterCallback ? $scope.animatedIfEnterCallback : (function() {});
$animate.enter(clone, $element.parent(), $element, callback);

$animate.leave(block.clone, ($scope.animatedIfLeaveCallback || (function() {})));

An isolated scope is created due to the 'scope' parameter, requiring changes when transcluding the content. Another modification involves creating and utilizing a child scope from the directive's $parent scope:

 childScope = $scope.$parent.$new();

For more details and the complete source of the modified ngIf directive, refer to this Plunker. Please note this has only undergone limited testing.

There may exist simpler alternatives, potentially by not fully recreating the ngIf directive but instead crafting one with a template that incorporates the original ngIf within additional wrapper divs, like so:

template: '<div><div ng-if="localVariable"><div ng-transclude></div></div></div>'

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

Is there a way for me to retrieve a variable from outside a function?

I'm trying to access a variable outside of the function in Next.js. I want to retrieve the 'name' from the data object after making an API call. let getDetail = async () => { let body = { code: '12', provider: & ...

How to send parameters to the jQuery delete button click event handler

Here is the jQuery code I am working with: $('#btnDelete').click( function() {//Do the delete here via jquery post}); In my table, each row has a delete button like this: <a id="btnDelete">Delete</a> I need to pass parameters to t ...

Saving users' dark mode preference on my website

I recently implemented a dark mode feature on my website. However, I noticed that when I enable dark mode and then refresh the page or navigate away, the preference resets. To address this issue, I am looking to store the user's preference as a cookie ...

Changing the positions of objects on a resized HTML Canvas

I am currently developing a tool that allows users to draw bounding boxes on images using the Canvas and Angular. Everything was working smoothly until I encountered an issue with zooming in on the canvas causing complications when trying to draw bounding ...

Utilize Babel transpiling specifically for necessary Node modules

My current setup in nextjs is configured to handle ES6 code for IE11. module.exports = { poweredByHeader: false, distDir: "ssr_build", webpack(config) { config.node = { fs: "empty", net: "empty", tls: "empty" } config.plugins = config.plugi ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

Header vanishes while using a JavaScript function to search through an HTML table

I'm facing an issue with a search function in a php script. The search function, written in javascript, is designed to sift through the table below and extract matching content as the user inputs text into the search field. It looks specifically withi ...

Is there a specific requirement for importing a React component into a particular file?

I am facing an issue with my component and two JavaScript files: index.js and App.js. When I import the component into index.js, it displays correctly on the screen. However, when I import it into App.js, nothing appears on the screen. Here is the code fr ...

What is the best way to center my dropdown menu on the page?

Discover my exclusive menu by visiting this link. For those who are curious about the source code, here's the HTML snippet: <div id='menu-container'> <ul id='menu' class="menu"> <li class='active'>& ...

node.js is reporting that it cannot locate some of the modules

Attempting to execute a file using node run index.js within the flashloan test folder results in an error that keeps occurring... node:internal/modules/cjs/loader:1042 throw err; ^ Error: Cannot find module '/home/schette/Documents/flashloan test ...

unable to perform a specific binary operation

Is there an efficient method to achieve the following using binary operations? First byte : 1001 1110 Second byte : 0001 0011 Desired outcome : 1000 1100 I am looking to reset all bits in the first byte that correspond to bit values of 1 in the secon ...

Using a loop to iterate through a multidimensional array in Node.js or JavaScript, creating additional data and adding new key-value pairs

Here is an array of objects showcasing different intents and results : var finalresult = [{ "Date": "Wed Jan 15 2020 00:00:00 GMT+0530 (India Standard Time)", "data": [{ "intent": "delivery", "result": [{ "h ...

What is the correct way to navigate data through my Node.js API?

I am struggling with getting the JSON response to display at the /api/orders_count endpoint. Here is a breakdown of my setup: In my project, I have various files: Routes file - where the orders_count route is defined: routes/index.js const express = req ...

Setting up Highcharts version 7 heatmaps with npm in an Angular 6 environment

I am currently having an issue with initializing the heatmap lib in Highcharts 7.0.1 within my Angular 6 app via npm. Despite successfully running basic charts like line, spline, bar, etc., when following the documentation for the heatmap initialization, I ...

reqParam = $.getQueryParameters(); How does this request work within an ajax form

I've spent a lot of time searching, but I can't figure out what the code reqParam = $.getQueryParameters(); means and how it is used in Ajax JavaScript. I copied this Java script from a website as an example. If anyone has any insights, please he ...

Generate a CSV file using Javascript

I am working with an HTML table (table id='testTable') and a button in the HTML code: <button id="btnExport" onclick="javascript:xport.toCSV('testTable');">CSV</button> There is also JavaScript code involved: toCSV: func ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

Chrome/IE displaying text indentation issue within nested divs

Encountering issues with nested divs in Chrome and IE, while Firefox works smoothly. The outer div has both text-indent and margin-top styles set. The inner div's display style is block, so the content after it should appear on a new line without any ...

After the introduction of ReactiveFormsModule, the functionality of the Angular router has ceased

I am working on setting up a reactive form in Angular for a login page. Here is my login form: <form [formGroup]="loginForm" (ngSubmit)="login(loginForm.value)"> <div class="form-group"> <label for="username">Username</label> ...

Troubleshooting JQuery Variable Overwriting Problem

Here is the code snippet I am working with: <script> $(document).ready(function() { var settings_image ={ url:"<?php echo site_url('/cms/editor/upload/images');?>", method: "POST", fileName: "file", returnType: ...