Creating custom animations using CSS and passing parameters through Angular directives to dynamically transform the elements

I am currently working on creating a progress indicator using a circular design. In this setup, the circle is generated through an Angular directive, with the progress level being passed as an argument to the directive and values extracted using an Angular repeat method.

https://i.sstatic.net/VlNfN.png

However, I am encountering an issue where all the progress levels are receiving the same value despite passing different values for each.

In an attempt to update the progress level, I initially experimented with using jQuery's .css function like so, but it ended up assigning the same value to all progress levels:

$(this).find('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');

Subsequently, I tried embedding the progress styling using ng-style directly into the template, but that also resulted in all progress levels showing the same value.

<div class="ppc-progress-fill" ng-style="{'transform': 'rotate('+deg+'deg)', '-webkit-transform': 'rotate('+deg+'deg)', '-ms-transform': 'rotate('+deg+'deg)'}"></div>

The code snippet below showcases the relevant sections of the code structure:

AppModule.directive("skillWidget", function(){
    var linkFunction = function(scope, element, attributes){
      //console.log(attributes);
       scope.text = attributes["text"]; 
       scope.percent = attributes["percent"];

       percent = parseInt(scope.percent),
         deg = 360*percent/100;

         //console.log($(this).find('.ppc-progress-fill'));

        $(this).find('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');

        //$('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');

    }; 

    return {
      restrict: "E",
      templateUrl:"views/skillTemplate.html",
      link: linkFunction,
      scope: {
        text: "@text",
        percent : "@percent"
      }
    }
});

Below is the template structure:

<div class="progress-pie-chart"><!--Pie Chart -->
                    <div class="ppc-progress">
                        <div class="ppc-progress-fill" ng-style="{'transform': 'rotate('+deg+'deg)', '-webkit-transform': 'rotate('+deg+'deg)', '-ms-transform': 'rotate('+deg+'deg)'}"></div>
                    </div>
                    <div class="ppc-percents">
                    <div class="pcc-percents-wrapper">                 
                        <span>{{text}}</span>
                    </div>
</div>

What could be causing this inconsistency?

Additional information: The circular progress bar design is based on this example http://codepen.io/shankarcabus/pen/GzAfb.

Answer №1

To achieve this, my recommendation is:

  • Develop a function called scope.deg to supply the deg value to your view
  • Implement the normal style attribute to the ppc-progress-fill in the view, utilizing the deg() function we established below for the transformations
  • Eradicate any jquery code from your implementation

For demonstration purposes, I have created a plunkr available here: http://embed.plnkr.co/tzPVwVue8Jhi1iIvUMJ7/preview. While it lacks styling, I have used an image as a background for the ppc-progress-fill to make it easier to observe the rotation effect. If you alter the percentage displayed, you will notice the AngularJs logo rotating ;).

In my practice, I strive to maintain a clear separation between presentation elements (HTML and CSS) and the directive code. When working with AngularJs, I refrain from relying on jQuery unnecessarily, as most tasks can be accomplished without its use. This approach facilitated a smoother transition to AngularJs for me.

Wishing you success in your coding endeavors!

ps: For future inquiries, providing a functional snippet/jsfiddle/plunkr/etc. would greatly assist us in offering prompt assistance for issue resolution. ;)

Answer №2

It appears that the $(this).find(...) function operates at a higher level than expected, resulting in all .ppc-progress-fill elements being affected by the .css(...) styling. This causes all directives to display the same value regardless of input.

To ensure that only the specific element associated with the directive is targeted, utilize the element attribute in your link function as specified in the Angular documentation:

element is the jqLite-wrapped element that this directive matches.

element.find('.ppc-progress-fill').css('transform','rotate('+ deg +'deg)');

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

Retrieving Data Dynamically from a MEAN Stack Database Using Variables

I need to fetch data from MongoDB that matches a specific userId. Say I have the following data stored in the database: { "_id": "hjdhs88889dsijd8", "items": "xxxxxx", "userId": "A123" }, { "_id": "hjhuf77889dsijd8", "items": "xxxxxx", ...

Blazor: Passing a CSS class as a parameter to a child component

Is there a way to ensure css isolation works properly when passing a class as an argument to a child component? In the following code snippet, I anticipated the child component would display in blue, but that's not happening. Parent.razor <div cla ...

Uploading a CSV file in JSON format to Amazon S3 with Node.js

Within my nodejs server.js script, the following code snippet can be found: router.post('/submission', (req, res) => { let data_filtered = req.body.data }) Upon user submission of a csv file, I am successfully retrieving it on the backend. ...

Are there any specific requirements or preferences for using .0 in em?

I'm struggling to find a concrete solution. In a nutshell, would it be more appropriate to utilize font-size: 2.0em; or font-size: 2em;? ...

Filling a table cell with a div that spans 100% height

I am currently working with Bootstrap and I am attempting to create three columns filled with text overlaying a rectangle. The squares within the columns should have equal height and there needs to be spacing between them. Through the use of display:table ...

How can I send various maximum values to the Backbone template?

Although in theory, it may seem simple, I am unsure about the exact code to use. In a view, if I define a variable max that retrieves an attribute called points from a collection, I can pass this variable as an object into my template using maxPoints.toJS ...

Fetch Comments through API

The task at hand is to display the commit comments and descriptions on the front end of a website. Here's where the repository can be found: https://github.com/shannonhochkins/SassyGrids My attempt so far involves using this code snippet: $.getJSON ...

The socket.io-client could not be located on the running Node.js server

Setting up a fresh installation of Node, Express, and Socket.io on a Linux environment using npm. When attempting to run a sample from the official socket.io source, I encountered an error stating that the 'socket.io-client' module was not found ...

How to center align an HTML page on an iPhone device

I am currently testing a HTML5 webpage on my iPhone, utilizing CSS3 as well. The page appears centered in all browsers except for the iPhone, where it is left aligned. I have attempted to use the following viewport meta tag: <meta name="viewport" conte ...

Is there a way to post an array of MongoDB documents embedded in req.body?

How can I send the data from req.body to this MongoDB model using a POST request to '/add'? const QuestionSchema = new mongoose.Schema({ description: String, alternatives: [{ text: { type: String, ...

Discovering the selected row with jqueryIs there a way to locate

There is a table with rows and a button that allows you to select a row: <table id="mytable" class="table-striped"> <tbody> <tr id="1"><td>Test1</td></tr> <tr id="2"><td>Test2</td>& ...

Refreshing information within a table using Ajax Prototype

For my current project, I am utilizing PrototypeJS. I have implemented Ajax.PeriodicalUpdater to insert real-time data as required. However, I am facing an issue where the data is not getting replaced inside a specific table. Below is the HTML code snippet ...

Encountering issues with the functionality of async await

I am a beginner when it comes to utilizing the async, await, and promise features in JavaScript. My current focus is on: async function sendTextMessage(text) { console.log("----1----"); var messageData = { message: { text: tex ...

Limiting the height of a Bootstrap 4 column to match another column's height: A simple guide

I currently have a layout with two columns in a row. The left column has a fixed height determined by its content (height:auto), while the right column is longer and may overflow once it reaches the height of the left column. How can I make sure the right ...

"Pairing div/span elements with sprites for improved web

I've been updating my website by replacing most inline images with sprites. Here's a basic CSS code snippet for the sprite class: .sprite{ background-image:url(...); background-position:...; width: 16px; height:16px; } After learning that nest ...

How do I use regex to grab all the text between two specific headers?

I need help extracting text between two specific headings. I attempted to create a regex for this purpose, but it's not quite capturing what I want. Currently, it includes the heading and paragraph, but misses the last heading. My Current Regex: /^& ...

Is Javascript Profiling a feature available in Firebug Lite?

Exploring the world of JavaScript profiles, I decided to step away from the usual Chrome Developer tools. Can Firebug Lite for Google Chrome provide Javascript Profiling functionality? ...

universal live media streaming application

I am currently developing a client-server solution with the following behavior: - The server side (C++) sends frames in a standard format. - The client side (C++) receives, decodes, and displays these frames. My goal is to integrate this solution into a c ...

Is there a way to "stream" a specific part of my website to a separate window?

Is there a way to stream a specific container from my webpage to another window? The scenario is similar to a Point of Sale system, where there is an operator-facing display and a second customer-facing display. The operator-facing display will show all ...

Tips for altering the appearance of a button when moving to a related page

I have a master page with four buttons that have a mouse hover CSS property. Each button's corresponding response page is defined on the same master page. Now, I want to change the button style when the user is on the corresponding page. How can this ...