The ngView animation does not trigger upon initial page load

I've been struggling with a persistent bug on my website for the past few days, and I haven't been able to find a solution yet (perhaps because my knowledge in AngularJs is limited).

Currently, I am using the latest versions of Angular (v1.6.1), ngRoute, and ngAnimate.

The issue I am facing is that the ngView animation enter event does not trigger when the website is first loaded.

Below is the snippet of my code:

var app = angular.module('app', ['ngAnimate', 'ngRoute']);

app.animation('.view', function () {
  return {
    enter : function (element, done) {
      alert('enter');
      done();
    },
    leave : function (element, done) {
      alert('leave');
      done();
    }
  }
});

//Config

app.config(function ($routeProvider, $locationProvider, $httpProvider){

  $routeProvider.when('/test.php',{
    template : function () {
      return "<div>Welcome to test page</div>";
    }
  });
  $routeProvider.when('/test.php/:path',{
    template : function () {
      return "<div>Inside page</div>";
    }
  });

  $locationProvider.html5Mode({enabled: true, requireBase: true});
});

I have come across a similar issue reported on GitHub: https://github.com/angular/angular.js/issues/10536

Some sources claim that it's a "feature, not a bug." However, on the live website, the animation sometimes works while other times it doesn't (especially on Safari and mobile browsers).

When I deliberately slow down the template loading process:

$routeProvider.when('/test.php',{
    template : function () {
      return "<div>Welcome to test page</div>";
    },
    resolve: {
      message: function ($timeout, $q) {
        console.log('asdasa')
        return $q(function(resolve){
          $timeout(function () {
            resolve('message');
          },1000);
        });
      }
    }
  });
  $routeProvider.when('/test.php/:path',{
    template : function () {
      return "<div>Inside page</div>";
    },
    resolve: {
      message: function ($timeout, $q) {
        return $q(function(resolve){
          $timeout(function () {
            resolve('message');
          },1000);
        });
      }
    }
  });

Or when using PHP delay:

sleep(1)

The enter event seems to fire, but not consistently, especially when the browser caches or loads quickly.

There are various quick fixes available on GitHub, but I prefer more reliable solutions over temporary hacks. One such hack mentioned on GitHub no longer seems to work:

$rootElement.data("$$ngAnimateState").running = false;

I also attempted the following fix:

app.run(function($animate) {
  $animate.enabled(true);
});

However, this has shown erratic behavior and did not resolve the issue on Safari.

You can view an example on JSBIN

Thank you in advance for your assistance, and I look forward to your help!

Answer №1

Following several days of deliberation on GitHub, we successfully discovered a resolution:

In order to activate animations, we need to enable them in app.run (as they are deactivated by default). Depending on the scenario, animation may need to be disabled on the body and enabled directly on the view. Unfortunately, enabling animations on the [ng-view] element poses a challenge as we can't access the newly created node before $animate does. To bypass this, it is recommended to encapsulate the [ng-view] element within a container div.

HTML:

<div id="view-container">
   <div class="view" ng-view></div>
</div>

JS:

app.run(function($animate) {
  $animate.enabled(true);
  $animate.enabled(document.body, false);
  $animate.enabled(document.getElementById('view-container'), true);
});

However, simply enabling animations may not suffice as angular checks for document.hidden. When set to true, $animation ceases to function. To ensure continuous operation of $animation (despite potential impact on smoothness), it is necessary to overwrite the angular function:

app.value('$$isDocumentHidden', function() { return false; });

Voila! We trust someone will benefit from this insight!

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

Tips for refreshing jQuery to ensure it functions smoothly for subsequent tasks

I am facing an issue with running a second process under JQuery, as shown in the code snippet below: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> </head> <body> <script type=" ...

Is there a way to reach my vue instance while inside a v-for iteration?

When using a v-for loop, I encounter an error: <div v-for="index in 6" :key="index"> <div class="card h-100" style="margin-top: 200px;"> <a href="#"> <img ...

Securing API keys in JavaScript

Despite extensive research online, I have been unable to find a suitable solution to a common issue regarding API key protection. The website in question is completely public with no secure login area, relying on API calls to various third-party websites ...

Unable to determine the success of testing my catch block within the then clause

I'm a beginner in unit testing code and feeling a bit lost! I am attempting to throw an error for the function below to cover the catch block, but so far I have not been successful and I am not sure why. Function: public initialize(): Promise<thi ...

Continuously encountering the 403 Forbidden error when making a POST request to the

My react frontend is running at http://localhost:3000/ and express backend is at http://localhost:8080/ Whenever I attempt to submit the registration form, Chrome console shows an error: 'POST http://localhost:3000/api/users 403 (Forbidden)' ...

Tap here for supplementary HTML

My HTML code looks like this: <a class="link">text</a> <div class="items"></div> (function($) { var link = $('.link'); link.click(function(){ alert('it works!'); }); $('.items').each(fun ...

Whenever I refresh the page, the values remain the same and only update when I log in

Is it possible for the user's statistics to automatically update when they reload the page, based on the database? For example, if a user registers with Money-0, Diamond-0, Ruby-0 and then adds 10 money, can their stats be automatically updated to Mon ...

Enable the ability to click on a row within the angular chart

I recently acquired the demo from However, I am wondering how I can set up a clickable row to direct users to another webpage. Any guidance on this would be greatly appreciated. ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Utilizing setColumns() function within Google Charts for JSON data tables

Is there a feature in the Google Charts API that functions similar to setColumns() for working with JSON data? I'm aiming to reduce PHP calls by consolidating my data into a single array and then specifying which columns Google Charts should utilize. ...

Transferring data from localStorage to PHP server

After conducting research and referring to a book that delves into Ajax calls to PHP and the transfer of data between browser and server, I stumbled upon useful resources such as this guide on passing saved localStorage web data to a php script, which alig ...

Monitoring user engagement using Socket.io and Firebase

In my Node/Express app, I am working on monitoring active users without using sessions. The app relies on an external API for handling JWT tokens that are directly passed to the client for storing and subsequent API requests. To track active users, I am u ...

Start CSS3 Animation Automatically

I am working on a multi-page website with a slider that includes a CSS3 animation featuring the famous rocket animation. Here is the code snippet I used: #outerspace { position: relative; height: 400px; background: #fff; color: #fff; } di ...

The initial page of a Visual Studio ASP.NET MVC project displays the full URL

Recently, I began developing a new angularjs SPA combined with Microsoft ASP.net WEBAPI. On my server, the SPA app folder is located parallel to the APIs folder, meaning that my index file is within the app folder. To set things up, I right-clicked on the ...

Guide on extracting the text from the <script> tag using python

I'm attempting to extract the script element content from a generic website using Selenium. <script>...</script> . url = 'https://unminify.com/' browser.get(url) elements = browser.find_elements_by_xpath('/html/body/script[ ...

Guide: Displaying components within a Vue2 string

Within my Vue2 component, I am working with a string that looks something like this: <template> <div><h1>Hello World</h1> <div v-html="testString"></div> </div> </template> <script> exp ...

React is failing to display identical values for each item being mapped in the same sequence

I have implemented some standard mapping logic. {MEMBERSHIPS.map((mItem, index) => ( <TableCell className="text-uppercase text-center" colSpan={2} padding="dense" ...

Is there a way to customize the color of an element within CardHeader in MUI?

Is there a way to customize the colors of {note.title} and {note.category}? I have attempted to do so by creating a theme: const theme = createTheme ({ palette: { category: { color: blue } } }) Unfortunately, this appro ...

The combination of Firebase Storage's listAll() method and getDownloadURL() function is not functioning properly

I created a function in my utils file that is designed to find and retrieve the URLs of images stored within a specific folder on Firebase Storage. The folder path is "proj_name/screenshots/uid/" and it contains 8 images. I have imported this function into ...

When attempting to add a respond_to in ActionController, an ActionController::UnknownFormat error

After removing respond_to and render to view, everything seems to be working smoothly, but when I include the js render, I encounter an error. controller code : if params[:stock].present? @data = params[:stock] @stock = Stock.new_form_lookup(params[ ...