Transforming a value within a controller into a directive

I am uncertain if I am approaching this correctly, but my goal is to convert a piece of code from a controller to a directive. The reason for this change is that I want to reuse the code with different values without creating multiple large object literals. Instead, I plan to have one object and update the values dynamically. However, I am facing an issue with binding chartConfig in the directive. Can you advise if I am on the right track?

Below is the code snippet for my directive:

app.directive('percentageSquare', function(){
    return {
        restrict: 'E',
        scope: {
            bgClass: '@',
            percentage: '@',
            chartConfig: '='
        },
        link: function(scope){
            var fontSize = 80;
            var percentage = scope.percentage || 0;
            scope.chartConfig = {
                options: {
                    chart: {
                        // Custom chart settings go here
                    }
                }
            };
        },
        templateUrl: '/templates/dashboard/charts/PercentageChart.html'
    };
});

Here is the template used by the directive (PercentageChart.html):

<div class="drop-shadow">
    <div class="row">
        <div class="col-sm-12">
            <highchart config="chartConfig" class="{{bgClass||''}}" ng-show="true"></highchart>
        </div>
    </div>
</div>

This is how I am implementing the directive:

<percentage-square bg-class="bg-orange" percentage="23"></percentage-square>

After moving chartConfig to the directive, it no longer binds as expected. Do you have any suggestions on resolving this issue?

Edit

I made some progress with the following workaround:

scope.$watch(scope.chartConfig, function(){
    scope.chartConfig = {
       // Update Chart Settings
    };
});

However, I notice that the chart loads twice, resulting in duplicated animations. Any ideas on how to rectify this?

Answer №1

It appears that the solution lies in observing the variable chartConfig. To ensure it functions correctly, it should be enclosed within quotation marks. The use of scope.chartConfig resulted in a double-loading of the chart, whereas using 'chartConfig' loaded it just once and efficiently.

scope.$watch('chartConfig', function(){
    scope.chartConfig = {
       // Chart Settings
    };
});

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

Error: The specified JSON path for Ajax request could not be

Although my expertise lies in C++, I must confess that my knowledge about web development is quite limited. Therefore, please bear in mind that my question requires a simple answer. Recently, I stumbled upon a fascinating C++ library for creating a web se ...

Stop users from saving the page in Next.js

I'm currently working on a NextJs project that involves building an editor application. I want to ensure that the editor functionality does not work when users attempt to save the page in a different format, similar to how applications like Youtube an ...

Scrolling the Ionic framework to a position below zero

My ion scroll is synchronized with another component for scrolling. I achieve this by using the function scroll1.scrollTo(left, top, false); Unfortunately, this function does not allow scrolling to a negative position, such as scroll1.scrollTo(left, -50, ...

What is the process for converting an Angular UTC timestamp to a local timestamp?

Is it possible to convert a UTC timestamp to a local time timestamp using any function or method? I am sending the timestamp to angular moments, but the server's timestamp is in UTC. ...

Trigger a function following a collection update in Angular Meteor

I am in the process of developing a multiplayer game, and I would like a specific function to be triggered once the first player updates an "isStarted" field in the collection. Within my controller code: angular.module('mcitygame').directive(&a ...

Error: Unable to update Ember Array - Property 'destroy' cannot be read because it is undefined

Is there a way to efficiently update an Ember Array so that changes in the array reflect in the view? Take a look at this simplified code snippet - cacheArr: Em.A([]), count: 1, updateFxn: function() { this.incrementProperty(count); devObj = Embe ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

Indication of a blank tab being displayed

I'm struggling to get my Angular directives working in my project. I've tried implementing a basic one, but for some reason it's not showing anything on the screen. Can anyone help me troubleshoot this issue? Here is my JS code: angular ...

Iterate through the call feature repeatedly, ensuring that each call has a different iteration number assigned to a variable within the

I have a situation where I need to call a certain feature (which has validations) multiple times within a loop. Currently, my code successfully calls the feature 3 times. * def xxx = """ function(times){ for(i=0;i<times ...

Typing the url in the address bar when using Angular's ui-router

Two distinct states are present: .state('test', { url: '/test', templateUrl: 'js/angular/views/test.html', controller: 'UserController', }) .state('test.list', { url: ' ...

Conditional Matching with Javascript Regular Expressions

My strings are formatted like this: #WTK-56491650H #=> want to capture '56491650H' #M123456 #=> want to capture 'M123456' I am trying to extract everything after the # character, unless there is a dash. In that case, I onl ...

v-treeview component triggering method execution twice upon input

I'm facing an issue with my Vue component that contains a treeview. Upon selecting a node, the goal is to update an array and display the checkbox as selected. However, I'm encountering a problem where if I select elements from one folder in the ...

Is there a way to grab the inner content of an e-mail link by right-clicking on it?

I am currently developing a Chrome Extension that functions similarly to the "Search on Google" feature when you right-click on selected text. However, I am facing an issue with making it work when right-clicking on a mailto: email link. How can I extract ...

Protractor tests are successful when run locally, but encounter failures when executed on Travis-CI

I recently integrated end-to-end tests using Protractor into my AngularJS application. Testing them locally showed that they all pass, but upon committing to GitHub and Travis for CI, most of the tests fail. The failing tests seem to be those requiring na ...

How can we stop the Bootstrap carousel from pausing when the mouse hovers over it and keep it cycling automatically?

Is there a way to stop the Bootstrap carousel from pausing when hovering with the mouse and instead have it continue cycling through items automatically? I've tried changing the pause argument from "hover" as mentioned in the documentation, but when ...

How can I append a hash to a URL using JavaScript without causing the page to scroll?

Is it possible to add a hash to the URL without scrolling the page using JavaScript? I navigate to the page I scroll down I click on a link that adds a hash (for example: http://www.example.com/#test) The page should not scroll back to the top. What is ...

Nuxt.js static pages with relative URLs

I am currently working on developing static pages with Nuxt.js (MPA). After executing the generate command, I noticed that all the URLs in the <nuxt-link> tag start from the root directory, specifically /. For instance, my project structure looks lik ...

When items are removed client-side, the Listbox becomes null

Given a Web Forms project inherited by me, I am relatively new to the field of Web development. The page in question features 2 listboxes: lstCaseLoad, containing "Caseloads" (ID numbers), and lstAssignedCaseLoad, filled with Caseloads chosen by the Form U ...

invoking a boolean type JavaScript function

I'm currently working on calling a Page Method using AJAX. Take a look at the code below: <asp:Button ID="btn_upload" runat="server" CssClass="btnEffects" Text="Upload" onclick="btn_upload_Click" OnClientClick="return Validate();" /> ...

Navigating back to the previous page while retaining modifications using AngularJS

When I use the products table to conduct an advanced search, view details of a specific item and then click on the cancel button to return to the list, all my research inputs are reset... Is there a way for me to go back to where I was before? Can I retri ...