Using AngularJS to create CSS animations with @keyframes inside a directive is an innovative way

I'm facing a challenge with creating @keyframes animation CSS within an AngularJS directive function. The issue is that I need to use a variable from the scope to generate these keyframes, but I am unsure of how to retrieve it.

app.directive("myCSSDiv", function() {
    var css = "@keyframes myAnimation {";
    var nb_msg = ??? // In this line, I would like to access a variable like $scope.nb_msg but I am not sure how to do so
    if(nb_msg == 2) {
        css += "0%, 100% {left: 0px}";
        css += "30%, 60% {left: -100px}";
    } else if(nb_msg == 3) {
        css += "0%, 100% {left: 0px}";
        css += "15%, 50% {left: -100px}";
        css += "60%, 85% {left: -200px}";
    } else if(...) {
        ...
    }
    return {
        restrict: "E",
        template: css
    }
});

If you have any suggestions or solutions, I would greatly appreciate it! Thanks!

Answer №1

The directive's scope can be accessed in the linking function of the directive.
It is recommended to isolate the directive's scope and pass values as parameters rather than accessing the current scope directly.

To use a value in the template, you can access it through an attribute:

app.directive('myCssDiv', function () {
    function createAnimationCss(num_messages) {
        var css = '@keyframes myAnimation {';
        switch (num_messages) {
            case 2:
                css += "0%, 100% {left: 0px}";
                css += "30%, 60% {left: -100px}";
                break;
            case 3:
                css += "0%, 100% {left: 0px}";
                css += "15%, 50% {left: -100px}";
                css += "60%, 85% {left: -200px}";
                break;
            case ...:
                ...
                break;
        }
        return css;
    }

    return {
        restrict: 'E',
        template: function (tElem, tAttrs) {
            return createAnimationCss(parseInt(tAttrs.message));
        }
    }
});

Usage example:

<my-css-div message="{{num_messages}}"></my-css-div>

UPDATE:

If num_messages may change or be asynchronously initialized later on, use the linking function and $watch to monitor its changes:

app.directive('myCssDiv', function () {
    function createAnimationCss(num_messages) {...}

    return {
        restrict: 'E',
        scope: {
            message: '='
        },
        link: function myCssDivPostLink(scope, elem, attrs) {
            scope.$watch('message', function (newValue) {
                var num_messages = parseInt(newValue);   
                if (!isNaN(num_messages)) {
                    elem.html(createAnimationCss(num_messages));
                }
            });
        }
    }
});

Usage example:

<my-css-div message="num_messages"></my-css-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

Update the CSS class for multiple elements that share the same ID on an HTML page

I am trying to change the CSS class for multiple elements with the same ID on a page. I have attempted to do so, but it seems that the changes only apply to the first element and not the others. My Attempt: Here is an example of how the elements are disp ...

Replicating a Div Click Event using Enzyme and React

I've recently started working with Enzyme and writing tests for an application developed by a team. One of the test cases involves simulating a click on an element that toggles the display of a check-mark image. The application consists of a list wher ...

AngularJS: Simultaneous Login/Sign Up and Numerous Updates

I have some quick questions regarding AngularJS. 1- How can I implement login/sign up features in AngularJs similar to what we see on Facebook or other applications? 2- I have developed a single page app using Angular where users can enter data using a f ...

In Bootstrap 5, the Col elements do not behave as inline elements

I have been attempting to create a column with 3 elements in a row: 2 buttons and 1 select dropdown Initially, I was able to achieve this layout with three buttons. However, when I replaced one button with a select dropdown, it stopped functioning properl ...

Is it possible for me to trigger a custom event using an eventBus listener?

In the Vue component, I have the following setup: data: function() { return { quotes: [] }; }, created() { eventBus.$on("quoteWasAdded", message => { this.quotes.push(message); this.$emit("quotesWereUpdated", this.quot ...

Existing cookie is not defined when using ngCookies

I've been trying to solve this issue for hours now but haven't been able to figure out the cause. Essentially, I have a frontend built with Angular.js that attempts to log users in using ngCookies on Angular.js 1.3.15 and communicates with an au ...

Issues with Ajax functionality in Rails

I believe my lack of knowledge in Ajax might be the reason for this issue. My goal is to continuously make ajax calls to my server as I am creating a demo app for learning purposes. Below is the code snippet: Code from job_status/index.html.erb file &l ...

Using AngularJS to apply custom css to a tag within a directive for creating a Bootstrap sticky footer

Currently, I am in the process of developing my very first AngularJS application with Bootstrap as the responsive framework. In order to achieve a sticky footer, I usually utilize jQuery to determine the outerHeight of the footer and then apply that value ...

Developing a LoadRunner script to extract JSON data

I am currently working on creating a loadrunner 'js' file to extract specific data from a json file. The json file is hosted on a web server, which is not causing any issues in retrieving the data. However, my challenge lies in returning a partic ...

What is the best way to inquire (or conduct a Google search) on combining objects from various database models?

I'm faced with the challenge of displaying objects from two distinct mongoDB database models simultaneously on a single index page. Currently, these two sets of data are separated onto different index pages due to my lack of foresight. The issue I&ap ...

Utilize AJAX to dynamically insert data into the database

I have created a JSP page that displays records, and now I am looking to include a dynamic link or button in the JSP that allows inserting data into the database without needing to refresh the page. This link should open a pop-up window with input fields ...

Silver button seems blue on iPhone

After creating this html code for a blue login button: <div class="p12"> <input type="submit" value="Log In" class="button loginButton"> </div> I added the following CSS style to it: .loginButton { background-color:#627aad; border:1px ...

Shift the input's focus after altering the select option using Element UI and Vue.js

When choosing a product from the selection menu, be sure to click on the desired product and then focus on the quantity input field. If you are having trouble using the ref attribute, check out the following link for more information: <el-select ...

Designing personalized plugins with Typescript in Nuxt

In my Nuxt project, I have implemented a custom plugin file that contains an object with settings called /helpers/settings: export const settings = { baseURL: 'https://my-site.com', ... }; This file is then imported and registered in /plugi ...

Automatically scroll the unselected tab to the bottom using code

Is there a way to smoothly scroll an inactive Chrome tab to the bottom without having to activate it? I have tried using code in the console, but it seems that the tab needs to be activated for the scrolling to work. Here is the code snippet I tested: win ...

Tips for adding two values simultaneously to an array in JavaScript

I am having trouble inserting two values into an array during each loop iteration. Here is the code I have tried: feature_arr = []; $form.find( '.variations .value' ).each( function() { var $radios = $( this ).fi ...

The CSS stylesheets are not compatible with IE7 and IE8

I am encountering an issue with my local site where the CSS links are not being included in the page, particularly in IE7 and IE8. The technologies I am using include WordPress 3.6, Bootstrap 3, Modernizr, and jQuery. Source Code <!DOCTYPE HTML PUBLI ...

Blazor: Personalizing color variables in _root.scss - A Step-by-Step Guide

Upon inspecting the generated project, I noticed a multitude of color variables such as --bs-body-bg. The developer tools indicate it is in _root.scss, however, that file appears to be non-existent and I suspect those variables may actually reside within b ...

Using 'jquery.get' in combination with a servlet is

I need a servlet that can handle GET requests and return a specific string. A simple example of the code is shown below: public class QueryHandler extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) ...

``Maintain user engagement with a dynamic menu by utilizing knockout for view switching and CSS

I'm facing a challenge with my single-page application developed using knockout/jquery. The issue lies in handling which view to display as the number of menu items increases, making the code more difficult to manage. I'm looking for a solution t ...