Using Angularjs: Trigger Directive Execution Post Completion of ng-init Function

I'm facing an issue with calling a function in ng-init within my HTML file. The function is responsible for making an API call and collecting data, which is then assigned to a scope variable and passed to a directive.

Initially, the controller gets executed first. However, before the API call completes, the directive is triggered. As a result, the scope variable passed to the controller remains undefined.

App.directive('foldertree', function () {
    return {
        restrict: 'A',
        scope: {
            'inputfromapicall': '=',
            'fileName': "="
        },
        link: function (scope, element, attrs, ngModelCtrl) {

            return $timeout(function() {               
                $('#divid').fileTree({
                    root: scope.inputfromapicall, //undefined
                    script: '/project/current/source/data/jqueryFileTree.jsp',
                    expandSpeed: 1,
                    collapseSpeed: 1,
                    multiFolder: false
                }, function (file) {
                    scope.fileName = file;                   
                    scope.$apply();
                });
            });
        }
    };
});

The above represents my directive code.

I apologize for any confusion caused by my initial question. I am hopeful that someone can assist me in finding a solution to this problem.

Answer №1

In comment scope.$watch done by MajoB, it solved the issue mentioned. Below is the revised code for my directive.

automateOnApp.directive('foldertree', ['$timeout', function($timeout){
    return {
        restrict: 'A',
        scope: {
            'inputfromapicall': '=',
            'fileName': "="
        },
        link: function (scope, element, attrs, ngModelCtrl, controller) {
            scope.fileName = '';
            return $timeout(function() {


                scope.$watch(function () {                           
                        return scope.inputfromapicall;
                }, function(newVal) {                      

                        if(!angular.isUndefined(scope.inputfromapicall)){
                            $('#divid').html('');
                            $('#divid').fileTree({
                                    root: newVal,
                                    script: '/project/current/source/data/jqueryFileTree.jsp',
                                    expandSpeed: 1,
                                    collapseSpeed: 1,
                                    multiFolder: false
                            }, function (file) {                        
                                    scope.fileName = file;                   
                                    scope.$apply();
                            });
                        }
                });

            });
        }
    };
}]);

May this code be beneficial to someone in the upcoming days.

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

Perform a POST request in JavaScript and handle the response in PHP

Currently, I am in the process of gathering data through a form and executing this JavaScript: fetch('process.php', { method: 'POST', body: formData, }).then(response => alert( response ) ); The execution of process.php hap ...

Executing jQuery function through variable reference

My goal is to modify the jQuery function being used based on the value of a switch statement. In this scenario, I want to select the element and then apply the appropriate jQuery function depending on the 'direction' parameter. $('#'+t ...

How can I calculate the width of a character in an HTML5 canvas?

When using the .fillText function with a fixed-width font, I can easily adjust the height by setting the .font property. However, is there a way to accurately determine the width of an individual character? ...

Apply bold formatting to the HTML text only, leaving the EJS variable untouched beside it

https://i.sstatic.net/X36eG.png Is there a way to format the text for "Guest signed up" and "Guests attended" in bold while keeping the values normal? Here is my current code: <li class="list-group-item">Guests signed up: <%= guestSignu ...

The search filter in Angular is limited in its ability to search through the entire table

I am facing an issue with the search filter in my table. Currently, it only searches records from the current page but I need it to search through the entire table. How can I modify it to achieve this? <input type="text" placeholder="Search By Any..." ...

Transforming JSON data from C# to AngularJS

My current challenge involves an array of file names: [HttpPost] public JsonResult GetJSONFilesList() { string[] filesArray = Directory.GetFiles("/UploadedFiles/"); for (int i = 0; i < filesArray.Length; i++) { ...

BookshelfJS: Establishing a One-to-One Relationship

Within my database, I am working with two tables - User and Address. The User table consists of the following two methods: shippingAddress: function() { var Address = require(appRoot + '/config/db').model('Address'); return thi ...

"Enhance Your Video Experience with a Personalized Play Button

Is it possible to customize the play icon for an embedded YouTube video? I came across a post discussing this topic: Can I change the play icon of embedded youtube videos? However, when trying to use something transparent as the new play button, the origin ...

Tips for preserving component state during page rerenders or changes

I created a counter with context API in React, and I'm looking for a way to persist the state even when the page is changed. Is there a method to store the Counter value during page transitions, similar to session storage? My app utilizes React Router ...

Issue with box shadow appearing incorrectly as element content increases in size while the body has an image background

After applying a box shadow to the header div, I noticed that the box shadow doesn't display properly when the hidden elements within the header are revealed. <div id="header"> <div id="logo"> <a href="#"><img src="logo.png" ...

The onRendered function fails to load all data in the template

I'm dealing with a frustrating bug that I just can't seem to fix. I've been attempting to load all users using Users.find() into one of my layout sub-templates, but for some reason, it's not working as expected. Instead of loading all u ...

Highcharts: Show tooltip above all elements

Is there a way to configure tooltip display above all elements? I want to define specific coordinates so that the tooltip remains open even if it is covering the chart, and only closes when interacting with the top block. Screenshot 1 Screenshot 2 For e ...

Disable onclick action for programmatically created buttons

I'm facing an issue with the code I'm using to delete messages on my website. The problem is that while newly added messages are being dynamically loaded, the delete button (which links to a message deletion function) does not seem to be working. ...

Repetition of UTM Parameters

I created a web page with a donation form embedded in it. Donors visiting the page come through a link that includes a source code at the end. I managed to include this source code in the URL of the embedded form using the following code: $(document).ready ...

An exclusive execution of the JavaScript function is ensured

I have a JavaScript function that I want to execute 12 times in a row. Here's my approach: Below, you'll find a list of 12 images: <img id="img1" src=""> </img> <img id="img2" src=""> </img> <img id="img3" src=""> ...

Utilize Google Chrome Developer Tools to interact with the "Follow" buttons on the webpage by clicking on them

https://i.stack.imgur.com/W32te.png Here is the script I am currently using: document.querySelectorAll('.components-button components-button-size-mini components-button-type-orange desktop components-button-inline').forEach(btn => btn.click() ...

tips for revealing content in a div by sliding from right to left

I came across a fiddle that animates from bottom to top when the cursor hovers over it. Is there a way to modify it so that it animates from right to left on click, and then hides the content? After hiding the content, I would like to have a button that a ...

JavaScript animation not functioning properly when height is set to "auto"

Can someone help me figure out why setting the height to "auto" in the code snippet below isn't working as expected? I want the DIV to adjust its size based on the content, but it's not happening. Any ideas on how to fix this issue would be great ...

I am having difficulty retrieving the user's IP address in VueJs

Here is the code snippet: Vue.mixin(windowMixin) export default { name: "App", methods: { getIpAddress(){ localStorage.getItem('ipAddress') ? '' : localStorage.setItem('ipAddress&apos ...

Replace the current CSS styles of a pre-installed package

I recently added a package for a type writer effect, but I'm having trouble with it not overriding the CSS styles I've set in the component. Here's an example of what I have: <template> <v-row class="hero" align-content= ...