The addClass function in AngularJS $animate does not seem to be triggering as expected

My current issue involves performing animation in Angular and encountering different results for similar instances.

Two scenarios are almost identical - one works perfectly while the other fails to animate, leaving me puzzled as to the reason behind its failure.

The first directive successfully animates a set of child elements within the element:

    dwApp.directive('introText', ['$animate', '$rootScope', function ($animate, $rootScope) {

    return {
        restrict: 'A',
        scope: {            
        },
        link: function (scope, element, attrs) {

            scope.animationStarted = false;

            $rootScope.$on('element-in-view', function (event, parent) {               
                if (!scope.animationStarted) {
                    scope.animationStarted = true;
                    $animate.addClass(element, 'slidein');
                };
            });
        }
    }

}]);


dwApp.animation('.slidein', function () {

    return {
        addClass: function (element, className) {
            TweenMax.staggerTo(element.children(), 2.8, { opacity: 0.85, left: '5%', ease: Circ.easeOut }, 3);  
        }
    }

});

The second direcive, however, does NOT work as expected: Despite successful console logging up until "

console.log('performing animation');
", it seems that the function isn't being triggered at all, leaving me baffled...

The HTML code is simply:

<mask></mask>

dwApp.directive('mask', ['$animate', '$rootScope', function ($animate, $rootScope) {

    return {
        restrict: 'E',
        link: function (scope, element, attrs) {

            console.log('mask directive')

            $rootScope.showMask = function () {
                console.log('showMask called - add class')
                $animate.addClass(element, 'showmask');
            };          

            // test
            $rootScope.showMask();
        }
    }

}]);


dwApp.animation('.showmask', function () {
    console.log('in showmask animation service');
    return {
        addClass: function (element, className) {
            console.log('performing animation');
            TweenMax.to(element, 1, { opacity: 1 });
        }
    }

});

Upon inspecting the HTML after calling $rootScope.showMask(), I notice that the mask now includes the class:

<mask class="showmask"></mask>

If anyone has any insights on where I might be erring, please share your thoughts!

Answer №1

The issue lies in the way you are testing the showMask() function.

Instead of

$rootScope.showMask()

try using

$timeout(function(){$rootScope.showMask()});

(Don't forget to add the necessary dependencies.) This way, the log message 'performing animation' will be displayed, and if tweenmax was included, it would likely do something as well.

http://jsfiddle.net/zQfxq/

Another person may need to explain why calling $rootScope.showMask() at that specific point is not behaving as expected. However, it seems logical to wait until everything is compiled and linked before testing, which is achieved with the $timeout.

Answer №2

Have you attempted utilizing the element variable for this purpose?

element.toggleClass('showmask')

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

extract the ID from an array and switch its state

I'm currently working on developing an "auto toggle" feature. My initial idea was to use a loop for this purpose. The array[i].onclick part is functioning as expected, but I am facing challenges in implementing the toggle animation. function setConte ...

Issue with Ng-style not functioning properly when setting background color

I am struggling to set the background of an element using a configuration object with ng-style. For some unknown reason, I can't seem to make it work and I'm finding it really perplexing. The element I'm attempting to configure: <div id ...

When utilizing React, I generated an HTML page with a distinct .js file, however, encountered two unexpected errors

Update : Gratitude to everyone who has helped me in tackling this issue. One user suggested using a web server, but my intention was to find a solution using just a single HTML and JS file. Even though I tried following the steps from a similar question o ...

Counting items in AngularJS filters: a step-by-step guide

I have a question regarding my jsfiddle example. Here is the link to my jsfiddle How can I ensure that it counts the number and only displays once instead of repeating multiple times? This is my HTML code: <section class="left" style="border-right:1 ...

What could be causing this error in a new Next.js application?

After multiple attempts, my frustration and disappointment in myself are causing a headache. Can someone please assist me? I am trying to create an app using the following command: npx create-next-app@latest --ts Immediately after running next dev, I enco ...

To access a different page, simply click the link and update the class on the new page

I am facing an issue with the tabs on my homepage. Currently, only one tab with the "current" class is visible while the rest are hidden. Is there a way to link from pageX to my homepage and specify which tab should be open? For instance, when clicking o ...

What is the method for tallying data during an ajax request?

When creating a pagination script using AJAX, I want to prioritize saving data consumption. My approach is to only load the items for the selected page and include empty li-elements with data-id attributes for those not displayed. However, I'm unsure ...

Give Jquery a quick breather

My goal is to have my program pause for 3 seconds before continuing with the rest of the code. I've been researching online, but all I can find are methods that delay specific lines of code, which is not what I need. What I would like to achieve look ...

Using AngularJS with Spring MVC and @RequestParam

As a newcomer to AngularJS, I have a Spring controller that retrieves an object from the database based on its id. I want to pass this id using @RequestParam in AngularJS. However, when attempting to do so, I encountered the following error message: "Error ...

Having difficulty assigning IDs and names to cloned elements after the first one

I am encountering an issue with setting the id of a cloned element. Initially, I have a partial view [mypartialview.cshtml] which contains a single element: @model mydata @{ Layout = null; } @Html.EditorFor(model => model.Details,"","supp_int_mat_de ...

Tips for executing an asynchronous fetch prior to the first rendering

Currently, I am working with the Wordpress API using Next.js on the front end. My goal is to fetch my navigation/menu data and have it pre-rendered. However, my attempts have only resulted in an empty <nav> </nav> element being rendered when I ...

Using Express.JS to attach a cookie to static content that is being served

I implement Express.JS to deliver static content: express.use(express.static('./../')); Whenever the server serves index.html, I want to include a cookie with the response to denote whether the user is logged in or not. Typically, one would uti ...

Enhancing the 'grunt build' process with partials for an AngularJS app

Is there a way to modify my Grunt file to ensure that it locates the partial views correctly? The grunt.js file I am using is the default one created when initializing an AngularJS application with Yeoman. It does not include any plugins or jQuery, just A ...

Developing a user-friendly widget for a website that is not optimized for mobile devices

Here's the backstory: I'm currently in the process of creating a mobile-friendly widget for my clients. Unfortunately, they have web pages that are not optimized for mobile devices, and it doesn't seem like that will change anytime soon. Th ...

Passing console.log as an argument in a JavaScript abstraction

Hey amazing minds of the coding world! I've embarked on a journey to learn JavaScript and I'm currently immersing myself in the Eloquent JavaScript book! At the moment, I am working on abstracting a for loop action with this code snippet... fu ...

Establishing the highest allowable value limit in cleave

I've integrated cleave.js into my Vue.js project to create a date input field. Here's the option configuration I used: <cleave :options="{ date: true, datePattern: ['m', 'd','Y'] ...

Shape with a dark border div

Having some trouble with creating this particular shape using CSS border classes. If anyone can assist in making this black box shape using Jquery, it would be greatly appreciated. Check out the image here. ...

Retrieve information from a JSON file by utilizing the JSON file itself as a variable

Currently, I am attempting to extract the URL of an attached photo using JSON. I am utilizing the value of the data from the JSON key "HousePhoto1" to then access the value from the post_media data. The issue I am encountering is that my JavaScript code fa ...

Unable to create a polygon on the Google Maps API using GPS coordinates inputted from a text field

I am currently developing an interactive map using the Google Maps API. The map includes a floating panel with two input fields where I can enter GPS coordinates. My goal is to create markers and connect them to form a polygon. While I can easily draw lin ...

Errors in Chartist.js Data Types

I am currently using the Chartist library to monitor various metrics for a website, but I have encountered some challenges with the plotting process. The main errors that are appearing include: TypeError: a.series.map is not a function TypeError: d.normal ...