Using AngularJS - Invoking a controller method within a directive

I am experimenting with combining jQuery Sparkline charts with Angularjs. To display multiple charts, I have opted to create a function in the controller and invoke it for each chart (directive).

JavaScript

controller

.controller('sparklineCtrl', [function(){

     this.sparklineBar = function(id, values, height, barWidth, barColor, barSpacing) {
           $('.'+id).sparkline(values, {
                type: 'bar',
                height: height,
                barWidth: barWidth,
                barColor: barColor,
                barSpacing: barSpacing
           })
      }

}])

directive

.directive('sparklineBar', function(){

        return {
            restrict: 'A',
            scope: {
                slBar: '&'
            },
            link: function(scope, element) {
                scope.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
            }
        }

    })

HTML

<div data-ng-controller="sparklineCtrl as spctrl">
      <div class="chart" id="stats-bar" data-sparkline-bar data-sl-bar="spctrl.sparklineBar()"></div>                                  
</div>

Upon running the above code, no errors appear in the browser console, but the chart does not render at all. I am unsure of what might be incorrect in my code. Interestingly, placing the function's code directly inside the directive makes it work.

.directive('sparklineBar', function(){

        return {
            restrict: 'A',
            link: function(scope, element) {
                $('#stats-bar').sparkline([6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], {
                    type: 'bar',
                    height: 45,
                    barWidth: 3,
                    barColor: '#fff',
                    barSpacing: 2
                })
            }
        }

    })

I prefer not using the above method as I require multiple charts. Any assistance on resolving this issue using controller functions would be greatly appreciated.

Answer №1

It's more efficient to transfer the function logic to a service or factory and then utilize Injection for your directive.

Here's an example:

app.factory('sparkService', function () {
 var ss = {} ; 
 ss.slBar= function(id, values, height, barWidth, barColor, barSpacing) {
       $('.'+id).sparkline(values, {
            type: 'bar',
            height: height,
            barWidth: barWidth,
            barColor: barColor,
            barSpacing: barSpacing
       });
 };

 return ss;
}

When implementing in the directive:

.directive('sparklineBar', ['sparkService',function(sparkService){

    return {
        restrict: 'A',
        scope: {
            slBar: '&'
        },
        link: function(scope, element) {
            sparkService.slBar('stats-bar', [6,4,8,6,5,6,7,8,3,5,9,5,8,4,3,6,8], '45px', 3, '#fff', 2);
        }
    }]);

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

Using the UI Bootstrap radio button within an ng-repeat loop

I'm attempting to create a series of radio buttons using ui bootstrap (http://angular-ui.github.io/bootstrap/) similar to the example on their website, but utilizing ng-repeat: <div class="btn-group"> <label ng-repeat='option in opt ...

Avoiding uib-popover from getting clipped by uib-carousel

I have a small widget with a popover that works fine when placed inside a div, but gets clipped when inserted into a carousel. Here's an example to illustrate what I mean: (The top image shows the widget in a div without clipping) https://i.sstatic. ...

Simultaneous addition in Meteor

Within my loop, I am creating objects where each new object relies on the ID of the previously inserted object. Unfortunately, it appears that at times the insertion process is not completed before moving on to the next iteration. As a result, the final o ...

Nested loops with synchronous calls running in parallel

Is there a way to make synchronous calls in two nested 'for' loops in Node.JS? I have an Asynchronous call, but I am unsure how to modify it to work synchronously and go to the next iteration when create_db is done! var new_items = []; f ...

methods to retrieve value from a javascript function

Just a quick inquiry - what's the best way to pass or return a value from a function? Here is my code: function numberOfDivs(){ var numberOfElements = $("#div").children().length; // Counting the number of existing divs return numberOfElements; } ...

Can you identify the animation being used on this button - is it CSS or JavaScript?

While browsing ThemeForest, I stumbled upon this theme: What caught my eye were the animation effects on the two buttons in the slider ("buy intense now" and "start a journey"). I tried to inspect the code using Firebug but couldn't figure it out com ...

Having trouble with the jQuery slideUp function?

Exploring some jQuery features for a trial run, I stumbled upon an unusual behavior. Perhaps someone in this forum can provide some insight. Keep in mind that this is all just test code, so please overlook any messy aspects. Currently, I am working with ...

Ways to eliminate toggle event in Angular

I've been doing a lot of research online, but all the solutions I find are using jquery. I'm still getting the hang of Angular and Typescript. I found this and this to be unhelpful. I built a monthpicker from scratch, which has a simple and clear ...

AngularJS special feature: enhance controllers and views by adding notification capabilities

What is the most efficient method for integrating common notification features into necessary controllers in AngularJS? The objective is to establish local notifications that can be effortlessly included or removed from any controller. Key factors includ ...

Update the value of an ASP textbox using JQuery, and ensure that the .Text property accurately reflects the new value

After searching extensively, I still haven't been able to find a solution to my problem. I am facing an issue with updating a readonly Textbox in ASP.NET using JQuery after selecting radio buttons. The value displays correctly and everything seems to ...

Change the content inside a div depending on the value of a button

I am currently exploring how to change the content of a div based on button values, utilizing angular2+. Below is my implementation in HTML and js export class TestComponent implements OnInit { title:string = "provas"; constructor() { } popula ...

Pressing Enter triggers Submit button twice

I’m currently working on a form that includes client-side JS validation using AJAX. The form is a simple contact form with three fields: name, email, and message. If you attempt to submit the form without proper validation, error message divs will appear ...

Prevent scrolling in AngularJS model popups

When loading data for the first time in a model popup, the scroll bar is not displayed inside the popup. However, after performing a search function and filtering the data, the scroll bar appears inside the model popup. How can this issue be fixed? this ...

Easily manipulate textboxes by dynamically adding or deleting them and then sending the data to a

Can you provide a simple example of how to dynamically add and remove textboxes and then display the results? I envision it like this: [Empty Textbox][Add button] When 'Value1' is entered into the textbox and 'add' is clicked, it s ...

An effective method for retrieving the attribute value of an array in AngularJS

I'm a newcomer to AngularJS and I have successfully retrieved data from SQL to AngularJS. Although I am able to display the data using ng-repeat, I am now interested in accessing a specific attribute of the array that I fetched from the database withi ...

What is the best way to ensure a DOM element exists before you can start manipulating it?

In my AngularJS application, I am utilizing Angular Material and md-select. When a user clicks on the md-select, a dropdown list appears and an overlay with the tag Name is added to the DOM. My goal is to add a class or style as soon as the user clicks on ...

Can I invoke a specific function from a controller in AngularJS?

I am new to developing in the MEAN stack and working on a Todo App where I create tasksheets and store todos within those specific tasksheets using AngularJS. Initially, I was retrieving all todos without considering which tasksheet they belonged to or cr ...

The onBlur() method is not functioning properly in JavaScript

Created a table using PHP where data is fetched from a MySQL database. One of the fields in the table is editable, and an onBlur listener was set up to send the edited data back to the MySQL table. However, the onBlur function doesn't seem to work as ...

Transforming an image object into a File object using Javascript

My goal is to utilize HTML5 on the client side in order to convert an "image object" into a "File object" for uploading to azure blob storage. I am working with AngularJs and my approach involves: Converting the image to a file Uploading the file to blob ...

Using a PHP variable to trigger the jQuery .show() function

I'm attempting to trigger jQuery .show() events based on PHP variables. Below is my PHP code (retrieved from a form submission on another page): $last_pic_displayed = trim($_POST["last_pic_displayed"]); if (strlen($last_pic_displayed) <= ...