Tips on utilizing $watch in this context to ensure the API is activated prior to the Directive, incorporating ui-router

I am currently using a ui-router and I have a question regarding the resolve function. Is it possible to use resolve with the following state configuration:

  state: {
     url: "/summary",
     templateUrl: '../script/planSummary.html',
     controller: "summaryCtrl",params:{obj:null}
    }
 }
]

My issue is that I need to trigger an API call before the directive in my controller runs. The directive requires data from the API to populate the page.

Currently, when the page loads, the directive fires because it's called in HTML, and then the API is triggered afterwards. Can anyone provide guidance on how to use the $watch function or suggest an alternative approach to ensure that the API is triggered before the directive?

Here is a snippet of the API code (trimmed for readability):

$timeout(function () {$http({
      method: 'GET',
      url: 'getPSDetails?psuid='+$scope.psuId,
        }).success(function (data) {
         console.log('success response');   }

$scope.summaryObject =data; // This is where all the data is retrieved

And here is a snippet of my Directive code (also trimmed for clarity):

myapp.directive('summaryFeatureDetails',function(){
    return{
        restrict: 'E',
        scope:true,
        controller:function($scope){

            $scope.columnPerPage = 5;
            $scope.currentPage = 0;
            $scope.currentColumns = [];
            $scope.controlData = [];
            $scope.totalNumberOfPage = Math.floor($scope.selectedData.length/$scope.columnPerPage);
            if (($scope.selectedData.length % $scope.columnPerPage) > 0){
                $scope.totalNumberOfPage = $scope.totalNumberOfPage + 1;
            }
    }
}

Answer №1

To ensure that the directive loads after the $scope.summaryObject is set, it is important to check if the object is not null before rendering the directive. One way to achieve this is by using the NgIf expression on the directive tag.

<yourDirectiveTag ng-if="!summaryObject" ></yourDirectiveTag>

Answer №2

Allow me to provide some guidance based on my experience. Here is an example of how I typically approach this:

Controller:

let controller = this;
controller.dataToDisplay = [];
...    
$http({
      method: 'GET',
      url: 'getPSDetails?psuid='+$scope.psuId,          
}).success(function (data) {
    Array.prototype.push.apply(controller.dataToDisplay, data);   
}

Directive:

myapp.directive('summaryFeatureDetails',function(){
    return{
        restrict: 'E',
        scope: {
            myData: '='
        }
        /* No controller */

HTML:

<summary-feature-details my-data="controller.dataToDisplay"></summary-feature-details>

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 JavaScript or jQuery to modify the URL of a webpage

Here is the HTML code I am working with: <form id="search-new"> <input type="text" name="search" placeholder="Search on the Site" value=""> <input id="search-submit" type="button" value="&rsaquo;"> </fo ...

Undefined value is returned by Ajax request

I am facing an issue with my ajax request: $.ajax({ type:'POST', url:'../php/anmelden_info.php', data:{ kat : 'Freizeitfussballer' }, success: function(data){ alert(data[0].anmelde_info); ...

Exploring potential arrays within a JSON file using TypeScript

Seeking guidance on a unique approach to handling array looping in TypeScript. Rather than the usual methods, my query pertains to a specific scenario which I will elaborate on. The structure of my JSON data is as follows: { "forename": "Maria", ...

Adjusting the border-right size based on scroll position

Apologies if this question seems trivial, but I am completely new to coding in HTML and JavaScript. I understand that I can make some changes based on scroll position, but right now I'm a little confused. I want to increase the height of a box as the ...

Error Encountered: Unable to Locate 'bootstrap' label in Bootstrap 5 Popover

I have been working on implementing a popover in my Angular 12 project using Bootstrap version v5.0.1. However, I am encountering a name error that I can't seem to resolve: var exampleEl = document.getElementById(item.name + index); var tooltip = ne ...

Is it possible in AngularJS to detect duplicates in the data.location and display each unique data.location only once?

Is there a way in AngularJS to identify duplicates in the data.location field and only display each unique data.location once? For example, instead of displaying: A Jane A Tom B Brian B Jane B Mike R Donald R ...

Utilize NodeJS to iterate through a string and retrieve the precise results

Within my NodeJS project, I have a string in the following format: "Package=Package&Qty=1&Price=123?Package=Package Two&Qty=3&Price=702?Package=Package Three&Qty=1&Price=199?Package=Package One&Qty=4&Price=852?" The string ...

Get the image data from a Nuxt 3 REST API endpoint

I've developed a straightforward API that fetches an image, performs transformations on it, and is supposed to return the modified image. Currently, I can only return a base64 string representation of the image. However, I'm unsure how to return ...

How can you decode JSON using JavaScript?

Need help with parsing a JSON string using JavaScript. The response looks like this: var data = '{"success":true,"number":2}'; Is there a way to extract the values success and number from this? ...

What is the best way to query the ng-model table using xpath in Selenium with Java?

I'm having trouble finding a table from DOCTYPE Html using xpath or className in Selenium/java. I can't seem to locate the locator. How can I retrieve the table using selenium java? Neither of the following paths are effective. You can view a sc ...

Reducer is not a standalone function in the realm of React Native's Redux framework

I need to implement a reducer in my react native application. The store constant is defined as follows: export const USER_PROFILE = 'USER_PROFILE'; This is the content of action.js file: import {USER_PROFILE} from '../constants/index'; ...

Explain the concept of DOM components in relation to refs within the React JS framework

Before this issue came up in the React documentation for ref forwarding, there was a mention: The concept of ref forwarding doesn't just apply to DOM elements. It can also be used with class components. There's a discussion on another platform ...

Retrieve the initial image link from a blogger's post in cases where it is not being stored on the Blogger platform for use in related

I am currently using a hosting service to store the images that I include on my blogger platform. However, I have encountered an issue where blogger does not automatically fetch the image url to use as the thumbnail when the image is hosted externally. C ...

Is it possible to pause code execution using async await?

As an experiment to understand async/await, I implemented the init function in a convoluted manner: function init() { console.log(1) accountsStore.getAccounts().then(() => { categoriesStore.getCategories().then(() => { she ...

Retrieve the offspring with the greatest level of depth within a parental relationship

Consider the following tree structure: -root | | |-child1 | |-innerChild1 | |-innerChild2 | |-child2 I am looking to create a JavaScript function that can determine the depth of an element within the tree. For example: var depth = getInnerDepth( ...

When modifying v-model directly in a Vue instance, the Vuetify component on the screen may not update its displayed value

Within my Vue component example (utilizing Vue 2 and Vuetify 1), I have implemented an input field for user data entry. However, I am looking to programmatically alter the input field's data to a specific value. For instance, in this scenario, I aim ...

Finishing up with regular expressions

I want to create an autocomplete feature for the input field on my website. For instance, when the tab key is pressed, I want the word htt to automatically become tp:// in the input value. This autocomplete should only work if the user inputs "htt" at the ...

What is the best way to tally a score after analyzing two spans in Javascript?

I have 3 spans where 2 contain an alphabet each. The third span is left blank for the result of comparing the first 2 spans. I need to display the result in the last span, showing a value of 1 if the two spans contain the same alphabet. Can anyone sugges ...

The data event request in express using nodeJS is experiencing difficulties

I am currently facing an issue with the data event while trying to upload files using Express. Despite adding console logging tests, the data event doesn't seem to be working properly. Below is the server-side code snippet: var express = require(&ap ...

"Troubleshooting: Why is my Bootstrap modal window only printing a

I've encountered an issue with printing the content of a Bootstrap modal window. Previously, the code I had was working fine but now it seems to be malfunctioning. Content is dynamically added to the form using appendChild() in a separate function. Ho ...