Invoke an AngularJS directive from a controller when clicked

Hey there! I'm currently utilizing the tg-dynamic-directive to loop through a JSON file and display the tree structure shown in the attached image.

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

One major issue I'm facing is performance degradation when the "tree" becomes very large, causing the browser to struggle with rendering numerous items (we're talking about cases where there are 1000 or more items). To address this, I am trying to load only the first two levels initially, keeping the rest collapsed. When a user clicks on the expand arrow of each element, I want to dynamically render its children by running the tg-dynamic-directive again.

During the initial template rendering process, I have included the following snippet to determine if it's the first two levels:

$scope.getView = function (item) {
    if (typeof item != 'undefined') {
        if(item.type == 'course' || item.type == 'label' || item.type == 'module' || item.type == 'course_assessment' || item.type == 'module_assessment') {
            return 'nestable_item.html';
        } else {
            return null;
        }
    } else {
        return null;
    }
};

Subsequently, I need to trigger the directive again when the expand arrow is clicked. Below is the directive in question:

angular.module('tg.dynamicDirective', [])
    .directive('tgDynamicDirective', ['$compile',
        function($compile) {
            'use strict';

            function templateUrlProvider(getView, ngModelItem) {
                if (getView) {
                    if (typeof getView === 'function') {
                        var templateUrl = getView(ngModelItem) || '';
                        if (templateUrl) {
                            return templateUrl;
                        }
                    } else if (typeof getView === 'string' && getView.length) {
                        return getView;
                    }
                }
                return '';
            }

            return {
                restrict: 'E',
                require: '^ngModel',
                scope: true,
                template: '<div ng-include="templateUrl"></div>',
                link: function(scope, element, attrs, ngModel) {
                    scope.$watch(function() {
                        var ngModelItem = scope.$eval(attrs.ngModel);
                        var getView = scope.$eval(attrs.tgDynamicDirectiveView);
                        scope.ngModelItem = ngModelItem;
                        return templateUrlProvider(getView, ngModelItem);
                    }, function(newValue, oldValue) {
                        scope.templateUrl = newValue;
                    });
                }
            };
        }
    ]);

My question is: How can I retrigger the tg-dynamic-directive when the expand arrow is clicked from the controller?

Answer №1

To trigger an event, you can use $rootScope.emit("XXXXXX"); and listen for it:

$rootScope.$on("XXXXXX", function() {
    // call your function here
})

You can also achieve this in a directive by calling the desired function, or by creating a dynamic directive using

document.createElement("tg-dynamic-directive");

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

Ways to eliminate a comma in a list without resorting to the replace method

I've encountered an issue with my original data containing commas. This data is in the form of a JSON object. When I read a file containing my JSON object using a BufferedReader, I add the output to a list. Although everything seems to be working fi ...

An issue arises with ReactJS MaterialUI Stepper when there is an overflow

My struggle with the Material UI Stepper component persists as I attempt to make it suit my requirements, specifically to display multiple steps and handle overflow. However, it stubbornly continues to misbehave by showing unusual separators when there is ...

What is the best way to halt the ticking of this clock in JavaScript?

I can't seem to figure out how to stop this clock using JavaScript Even though I press the stop button, the clock keeps running <!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to halt the clo ...

Optimal method for showcasing a large 2-dimensional array

I am considering displaying a 1000x1000 array with elements that are either black or white based on boolean values. I am contemplating using either javascript or winforms for this task, but I want to understand the potential drawbacks of each option befo ...

Using JavaScript and HTML to show the current month, date, and year on a webpage

I am looking to display not only the time, but also the month, date and year. My attempted solution involved creating variables for the month, day and year, and then using getElementById. Here is an example of what I tried: var d = date.getDay(); var mn ...

Whenever I attempt to import the "Highway" package, I encounter an error stating "Unexpected identifier."

After installing Highway through the terminal, I encountered an issue when running the script below: import Highway from '@dogstudio/highway'; import Fade from './transition'; const H = new Highway.core({ transition: { default: ...

Attempting to include html5shiv.js in my project to ensure compatibility with Internet Explorer for proper rendering

<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <meta name="Description" content="C.V"/> The code snippet below was added to try and render in Internet Explorer, unfortunately it did not work as expected. < ...

Why does the response.json() method in the Fetch API return a JavaScript object instead of a JSON string?

After using Body.json() to read the response stream and parse it as JSON, I expected to receive a JSON string when I logged the jsonData. Instead, I received a Javascript object. Shouldn't jsonData return a JSON string until we call JSON.parse() to co ...

javascript varying functionality between Chrome and Firefox

My Grease monkey script/Tamper monkey is designed to click on buttons that contain the word 'attach'. Although it works perfectly, I have noticed a difference in behavior between Chrome and Firefox. In Firefox, the clicks occur in the order of a ...

Efficiently shrink column width in Material-UI's <TableRow/> using ReactJS and Material-UI

At the moment, I am utilizing ReactJS along with Material-UI. One issue I am encountering is that when using Material-UI's <Table>, the columns' width are automatically set based on content which results in all columns having equal width. H ...

My website has a navbar button that is not directing to the intended section of the screen

I have created this HTML code for my Navbar buttons: <button class="navbar-toggle" data-toggle = "collapse" data-target=".navHeaderCollapse"> <span class="icon-bar"></span> <span class="icon-bar">< ...

Converting JSON data into rows within a Postgres stored procedure: A step-by-step guide

Currently, I am faced with the challenge of creating a stored procedure in Postgres. The data that I have in Postgres is structured as JSON, as shown below. { "identifiers": [ { "identifierType": ...

Deactivate particular JavaScript when displaying a Bootstrap modal

On mobile devices, I have JavaScript that is preventing vertical panning on modals, resulting in users not being able to see all the modal content. Is there a way to disable this JavaScript when a modal is displayed? The following snippet of JavaScript a ...

Having trouble with updating PHP MySQL data using serializeArray?

My HTML page includes a display of temperature with two buttons - one for updating MySQL with the temperature setting and the other for toggling on/off data. Previously, everything was functioning correctly with the initial code: function myFunction() { ...

Successive Alerts with Material-UI and React-Redux

After realizing that having multiple snackbars scattered across different components was messy, I decided to revamp my app by creating a single custom component that can be called using Redux to display any type of snackbar needed. Desired outcome: I exp ...

The method for transforming all headers into permalinks with jquery/javascript

I am looking for a way to transform all headers on a page into clickable permalinks using jQuery or JavaScript. Here is the HTML code: $('h3').each(function() { var id = $(this).attr('id'); if (id) { //Check if the element has a ...

The reactivity of VUE 3 arrays is not being updated, but individual array elements accessed using array

Currently facing an issue while trying to connect a dynamically updating array of objects to a Konva circle. The circles are appearing as expected, but the problem arises within a for loop where I update player locations based on a "tick". While setting th ...

Upload the PDF file along with other form data in a React application

I'm currently facing an issue with using formData for submitting a pdf file const [file,setFile] = useState() const [isFilePicked, setIsFilePicked] = useState(false); I have an input of type file <input accept=".pdf" type="file&quo ...

Instructions for setting up a "beta edition" with npm or bower

Is there a way to download Dojo version 1.11.0-pre using npm or bower? I have tried adding the dependency in my package.json file, but npm is unable to locate it. Any suggestions on how to resolve this issue and successfully load Dojo 1.11.0-pre? { " ...

Performing an API GET request in a header.ejs file using Node.js

Looking to fetch data from an endpoint for a header.ejs file that will be displayed on all routed files ("/", "/news" "/dogs"). Below is my app.js code: // GET API REQUEST var url = 'https://url.tld/api/'; request(url, function (error, response, ...