The drop-down component is being filled with data but unfortunately, only dummy data is functional at the

Having trouble populating data in the drop-down component. Everything works fine when using dummy JSON data as shown in the comments.

The GET request service retrieves the necessary data, and then I assign the response to the appropriate variable. The GET service and drop-down component are located in another View component.

No error message in the console... what am I missing here?

Code for the GET requests service:

(function () {
    "use strict";
    angular.module('app').factory('GetService', function ($http) {
        return{
            get: function (uri, config) {
                $http.get(uri, config).
                    then(function(response) {
                        return response.data;
                    });
            }
        }
    });
}());

Code for the drop-down component that accepts JSON data:

(function () {
"use strict";

var module = angular.module("app");
module.component("dropDown", {
    template: 
    <div class="input-group">
        <span class="input-group-addon">{{vm.placeholder}}</span>
        <select class="form-control"
            ng-model="vm.selectedItem"
            ng-options="option.name for option in vm.items"></select>
    </div>,
    controllerAs: "vm",
    bindings: {
        placeholder: '@',
        itemlist: '='
    },
    controller: function() {
        var vm = this;
        vm.items = vm.itemlist;
        vm.selectedItem = vm.itemlist[0];
    }
});
})(); 

Code for the View component:

(function () {
    "use strict";
    var module = angular.module('app');

    function controller(GetService) {
        var vm = this;
        vm.$onInit = function () {              
            vm.doprdown1url = "/Controller/Action1";
            vm.doprdown2url = "/Controller/Action2";
            vm.dd1List = [];
            vm.dd2List = [];
            GetService.get(vm.doprdown1url, null).then(function (data) {
                vm.dd1List = JSON.parse(data.data);
            });
            GetService.get(vm.doprdown2url, null).then(function (data) {
                vm.dd2List = JSON.parse(data.data);
            });
            //vm.dd1List = [{
            //    id: 0,
            //    name: 'Arm'
            //}, {
            //    id: 1,
            //    name: 'Leg'
            //}, {
            //    id: 2,
            //    name: 'Hand'
            //}];

            //vm.dd2List = [{
            //    id: 0,
            //    name: 'Eye'
            //}, {
            //    id: 1,
            //    name: 'Nose'
            //}, {
            //    id: 2,
            //    name: 'Ear'
            //}];
        }
    }

    module.component("view1", {
        template: 
        <p>
           <drop-down placeholder="Title" itemlist="vm.dd1List"></drop-down>
           <drop-down placeholder="Title2" itemlist="vm.dd2List"></drop-down>
        </p>,
        controllerAs: "vm",
        controller: ["$http", controller]
    });
}());

Answer №1

One reason for this issue is that all templates are loaded before the service returns any data. To tackle this problem, one option is to use a timeout function, although it may not be the most elegant solution. (refer to the snippet below, where you have to wait 5 seconds to see the result)

A more effective approach is to have the child component call the service using the require option

function FetchData($http) {
  return{
    get: function (url, config) {
      $http.get(url, config).
      then(function(response) {
        return response.data;
      }, function(response) {
        return response;
      });
    }
  }
};
var dropdownComponent = {
    template: `
    <div class="input-group">
        <span class="input-group-addon">{{$ctrl.placeholder}}</span>
        <select class="form-control"
            ng-model="$ctrl.selectedItem"
            ng-options="option.name for option in $ctrl.items"></select>
    </div>`,
    bindings: {
        placeholder: '@',
        itemlist: '='
    },
    controller: function($timeout) {
        var vm = this;
        $timeout(function() {
          console.log(vm.itemlist);
          vm.items = vm.itemlist;
          vm.selectedItem = vm.itemlist[0];
        }, 5000);
    }
};
function MainController(FetchData) {
  var vm = this;
  vm.$onInit = function () {              
    vm.url1 = "https://randomuser.me/api/";
    vm.url2 = "https://randomuser.me/api/";
    vm.list1 = [];
    vm.list2 = [];
    FetchData.get(vm.url1, null).then(function (data) {
      console.log(data.data.info.seed);
      vm.list1 = [{id: 1, name: data.data.info.seed}];
    });
    FetchData.get(vm.url2, null).then(function (data) {
      console.log(data.data.info.seed);
      vm.list2 = [{id: 1, name: data.data.info.seed}];
    });
  }
};

var viewComponent = {
  template: `
  <p>
  <dropdownComponent placeholder="Title" itemlist="$ctrl.list1"></dropdownComponent>
  <dropdownComponent placeholder="Title2" itemlist="$ctrl.list2"></dropdownComponent>
  </p>`,
  controller: ["$http", MainController]
};

angular.module('myApp', []);
angular
    .module('myApp')
    .factory('FetchData', FetchData)
    .component('dropdownComponent', dropdownComponent)
    .component('viewComponent', viewComponent);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<div ng-app="myApp">
    <viewComponent></viewComponent>
</div>

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 8007 encountered when attempting to scale at 100% proficiency. Transformation unsuccessful

Wondering if this could be a bug in Photoshop. When scaling a layer and entering values of 100%, an error message pops up: var srcDoc = app.activeDocument; var numOfLayers = srcDoc.layers.length; // main loop for (var i = numOfLayers -1; i >= 0 ; i-- ...

An issue occurred with lodash during the construction of /@types/lodash/common/object.d.ts at line 1188, character 142: Expected '('

Things were going smoothly, but out of nowhere my build started failing. Here are the errors that are popping up: ERROR in /node_modules/@types/lodash/common/function.d.ts (852,68): ';' expected. ERROR in /node_modules/@types/lodash/common/commo ...

Twitter typeahead with a dynamic array of strings

Currently, I am making an ajax call to retrieve a list of objects. Once this array of objects is filled, a separate string[] is created with the names of these objects. My goal is to pass this data to Twitter Typeahead using a Bloodhound source. However, ...

Optimize Google Places Autocomplete: Customize the way search results are shown after selection (display only street name and number)

Struggling to update Google's autocomplete input value to only show the selected "streetname number" instead of the full address. It works when the user hits enter, but the value changes back when the input field loses focus. Looking for a simple sol ...

Flow of logic for AngularJS ns-show

Being a newcomer to angularjs, I am exploring ways to display an html element based on a property of the $scope object without utilizing any form element. Here is the code snippet: <div id="ListApp"> <div ng-controller="ListCtrl"> ...

What techniques can you leverage in React to iterate through nested arrays, such as using .map or other alternatives?

As part of my work, I often come across an Array structure similar to the one below: Array = [ { product1, orderedBy = [{customer1}, {customer2},.....,{customerN}] }, { product2, ...

Activate an asynchronous request within a dropdown menu that was loaded using ajax

Let me start by presenting a simplified version of my code: HTML : <form id="add"> <select id="cat"> <option selected value="">…</option> <option value="a">A</option> <option value="b"& ...

A guide on mapping an array and removing the associated element

I have an array called responseData, which is used to display the available card options on the screen. public responseData = [ { id: 1399, pessoa_id: 75898, created_at: '2022-11-08T16:59:59.000000Z', holder: 'LEONARDO ', validade: ...

In Javascript, you can enhance your axes on a graph by adding labels at both the

Is there a way to add labels at the beginning and end of the axes to indicate the importance level, such as "not very important" and "very important"? I am currently utilizing a slider program from here. Since I am new to JavaScript, I would greatly appre ...

What is preventing me from displaying my paragraph?

I have some content that I want to show a paragraph with the class paragraphtoggle when clicked, but it's not working as expected. Here is what I have tried: https://example.com/jsfiddle HTML <div class="enzimskiprogramindex herbaprogramindex he ...

Is it possible to utilize jQuery for extracting information from HTML pages?

During my project research involving parsing and extracting content from HTML pages, I stumbled upon jQuery. Can jQuery be used for this purpose? If yes, could someone provide examples or share tutorial links with me? One idea I have is to parse the top q ...

Exploring the process of passing an array as a function argument from PHP to JavaScript

I am looking for assistance in passing an array as a function argument from PHP to JS. The values I need are retrieved from a database. while ($rows = pg_fetch_array($qry)) { ?> <option value="<?php echo $rows[&ap ...

Updating information dynamically in a controller based on an ng-repeat from a different controller in AngularJS

To enhance comprehension, I've created a straightforward example. For this scenario, ng-repeat is used to call a template that has its own controller. However, the controller of the template requires injected data from a service for each ng-repeat it ...

When attempting to run npm run build for a Next.js application on an EC2 instance, it unexpectedly terminates on its own

While attempting to deploy my Next.js app on EC2, I encountered an issue where the npm run build command was being automatically killed. Suspecting it may be due to insufficient RAM, I switched to an instance type with 4GB of RAM (t3.medium), but the probl ...

Having trouble converting NSData object to NSDictionary

Could there be an issue with the JSON output that is causing strange encoding when trying to extract information from a JSON file found on a blog? JSON: [{ "title": "A visit to McSorley\u0027s Old Ale House", "subtitle": "", "summary": "&bs ...

Exploring dependency injection in Angular 1 using a blend of JavaScript and TypeScript

I'm currently working on integrating TypeScript into an existing Angular 1.5 application. Despite successfully using Angular services and third-party services, I am facing difficulties in injecting custom services that are written in vanilla JavaScrip ...

What is the best way to consistently include a query string such as lang=en in Angular requests?

We have recently implemented I18N and added a language switcher in our menu to allow users to switch between en, jp, and fr languages. Once the language is switched, the URL changes with a query string appended at the end: http://localhost:3030/loadTests? ...

Donut visualization within a Sankey diagram using D3 JS

Looking to enhance my D3 Js Sankey diagram by adding a donut chart around the company circles. The donut chart will display two values, numsms and nummid, within the company node. Below is an example of what I am trying to achieve: However, I've been ...

Utilizing custom i18n blocks for Vue 3 and Vuetify 3 to enhance locale messages

Looking to localize messages separately for each component? Check out this example for Vue 2. But how can it be done for Vue 3 and Vuetify 3? Here's what I've tried: package.json "dependencies": { "@mdi/font": "6.5 ...

Using jQuery, include a variable within an anchor tag

Struggling to insert a variable into a jQuery link, but my attempts have all failed. Check out this example: let url = "www.google.com?s=" + id; $("#test").append("<a href='" + url + "'>Test</a>"); ...