Problem with AngularJS Select Box

My AngularJS dependable dropdowns are currently functioning well with static data from a script file. However, I am now looking to bind data to these dropdowns from a URL. The challenge is that I don't have a separate URL for the dropdowns; there is just one URL that delivers all the necessary data.

How should I approach parsing the data in order to achieve the desired output? I am relatively new to this, so any assistance would be greatly appreciated!

Answer №1

Original Punker solution:

http://plnkr.co/edit/okKOeQViflRseqrOYeOY?p=preview

Your question and demo don't align in this case.

The JSON data can be parsed directly using Angular, eliminating the need for an ng-change function to track dropdown selections. See the code snippet below for an example of parsing data within the HTML itself.

                <div class="col-sm-4">
                    <am-multiselect class="input-lg"
                                    template-url="multiselect.tmpl.html"
                                    ng-model="selectedcountry" ms-header="Select country" style="width:200px;"
                                    options="c.CountryName for c in table"
                                    ng-change="setState(selectedcountry)"
                                    change="selected()"></am-multiselect>



                </div>
            </div>
            <div class="form-group">

                <div class="col-sm-4">
                    <am-multiselect class="input-lg" multiple="true" ms-selected="{{selectedState.length}} State(s) selected"
                                    ng-model="selectedState" ms-header="Select States"
                                    options="s.STATE for s in table"
                                    ng-change="setCity(selectedState)"
                                    template-url="multiselect.tmpl.html" style="width:500px;"
                                    change="selected()">
                    </am-multiselect>

                </div>
            </div>

            <div class="form-group">

                <div class="col-sm-4">
                    <am-multiselect class="input-lg" multiple="true" ms-selected="{{selectedCity.length}} City(ies) selected"
                                    ng-model="selectedCity" ms-header="Select City"
                                    options="m.CityName for m in table"
                                    template-url="multiselect.tmpl.html" style="width:500px;"
                                    change="selected()"></am-multiselect>

                </div>
            </div>

The second dropdown for STATE doesn't trigger a change even when the scope is updated.

Using a $watch can help monitor scope changes and apply them to the CITY dropdown.

Modify your JavaScript as follows:

angular.module('app', ['am.multiselect']);

angular.module('app')
  .controller('ctrl', function($scope, $http, $location, $filter,$window) {

    var tableData = {
      "Table": [{
        "CountryUid": 3,
        "CountryName": "INDIA",
        "STATE": "AndraPradesh",
        "CityId": 3,
        "CityName": "Vijayawada"
      }, {
        "CountryUid": 2,
        "CountryName": "USA",
        "STATE": "Florida",
        "CityId": 3,
        "CityName": "Tampa"
      }, {
        "CountryUid": 3,
        "CountryName": "INDIA",
        "STATE": "Assam",
        "CityId": 3,
        "CityName": "Jorhat"
      }]
    };

    var countries = [];
    var states = [];
    var cities = [];

    $scope.table = tableData.Table;
    $scope.countries = countries;
    $scope.states = states;
    $scope.cities = cities;
    $scope.selectedsite = null;
    $scope.selectedState = [];
    $scope.selectedCity = [];

    $scope.setState = function(country) {
      $scope.selectedStates = tableData.Table.filter(function(el) {
        return el.CountryName === country
      });
      $scope.selectedState = $scope.selectedStates.map(function(elm) {return elm.STATE;});
    }
    $scope.setCity = function(state) {
      selectedCity = tableData.Table.filter(function(el) {
        return el.STATE === state
      });
      $scope.selectedCity = selectedCity.map(function(elm) {return elm.CityName;});
    }
    $scope.$watch('selectedStates', function(newVal, oldVal, theScope) {
      $scope.selectedCity = newVal.map(function(elm) {return elm.CityName;});
      console.log(newVal,$scope.selectedCity);
    });

Note: The provided Plunker may have minor issues that you can address on your own.

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

What is the best way to gradually transform a continuously shifting text color into a single, consistent hue?

Hey there, wonderful people of StackOverflow! I am absolutely stumped and cannot figure out how to smoothly transition this color-changing text from its current state into a different solid color when the submit button is clicked. Is there a skilled indiv ...

Using a bound data variable in a filter within an ng-repeat loop (Angular JS)

<!-- Left Navbar --> <div class="container-fluid" style="margin-top: 50px"> <div class="row"> <div class="col-sm-3 col-md-2 sidebar"> <ul ng-repeat="type in types" class="nav nav-sidebar"> <li>{{ ...

Typescript indicates that an object may be potentially null

I've hit a roadblock where I keep getting warnings that the objects might be null. After searching online and on StackOverflow, I've tried numerous solutions with no luck. My goal is to insert the text "test" into the HTML elements using their ID ...

Can you explain the concept of Cross-origin requests?

My JavaScript application is designed to detect single, double right, and double left clicks. A single click triggers an asynchronous request to the HTTP server, while the rest are intended to change the user interface on the client side. However, I am str ...

Caution: React is unable to identify the `PaperComponent` prop on a DOM element

Trying to create a draggable modal using Material UI's 'Modal' component. I want users to be able to move the modal around by dragging it, so I decided to use 'Draggable' from react-draggable library. However, I encountered this er ...

Utilizing AngularJS to display a table with Rowspan functionality and the ability to filter elements

I am trying to develop an HTML table that utilizes rowspan with ng-repeat to group data effectively. The overall layout is functioning as expected, but I encountered a problem when attempting to apply filters to the table. Specifically, when I filter the ...

Oops, it seems like there was an issue with NextJS 13 Error. The createContext functionality can only be used in Client Components. To resolve this, simply add the "use client" directive at the

**Issue: The error states that createContext only works in Client Components and suggests adding the "use client" directive at the top of the file to resolve it. Can you explain why this error is occurring? // layout.tsx import Layout from "./componen ...

Unexpected behavior observed with callback function when inserting a query in Node.js

Having a minor issue with using the POST method and adding an INSERT. The functionality works correctly as shown below, but I am looking to implement a callback after the data has been inserted. Currently, the database is updated successfully, but I am una ...

Confirm that the method has been called by utilizing the AVA testing framework

As I work on creating a unit test for my React component using tools like Ava and Enzyme, I encounter an issue. My goal is to create a simple unit test that checks if a certain method has been called. The test should pass if the method has indeed been call ...

Is there a way to split each foreach value into distinct variables?

I am looking to assign different variables to foreach values. I have fetched data from an API in JSON format, and then echoed those values using a foreach loop. My goal is to display the echoed value in an input box using JavaScript. I attempted the follow ...

Adapting Your Cards: How can you effectively showcase a random JSON object?

I want to create an adaptive card that includes a JSON object of unknown structure. The JSON object is expected to be simple, possibly just key-value pairs. Since I won't know the structure until runtime, I can't template this part of the card. ...

Picking specific <button> items

Presented here are a series of buttons to choose from: <button id="hdfs-test" type="button" class="btn btn-default btn-lg">HDFS</button> <button id="hive-test" type="button" class="btn btn-default btn-lg">HIVE</button> <button id ...

Guide to Spidermonkey Bytecode Documentation

I've been searching for a comprehensive guide to spidermonkey's bytecodes for some time now, or at least something that gives me an overview of their purpose. Does anyone know of a good resource for this? Thank you! ...

Issue with $sce.trustAsResourceUrl(url) function in angularJS

Having trouble with loading a file into an iframe. Here is the code for the iframe: <iframe width="100%" height="800px" scrolling="no" ng-src="{{someUrl}}"></iframe> In the controller, I am trying to: $scope.someUrl = $sce.trustAsResourceUr ...

"Efficiently sharing information in a multi-tenant application: strategies for seamless data transfer between front

In my development of a multi tenancy application using Node.js/Mongoose and React, I made the decision to utilize a single database for all users. The main collection, dubbed companies, serves as storage for basic company data and includes a unique compan ...

Encountering a build time issue while incorporating Redis into Next.js

Incorporating Redis into my Next.js project has been beneficial overall. However, during the build process (next build), an error arises when it attempts to connect to Redis, resulting in the following message: Collecting page data ..[ioredis] Unhandled e ...

Error encountered while compiling React application: Module build unsuccessful due to failure in ./node_modules/babel-loader/lib/index.js

Having an issue while trying to compile a React app. After pulling the repo from Github, running yarn install, and then compiling it, I encountered the following error: Module build failed (from ./node_modules/babel-loader/lib/index.js) SyntaxError: {file_ ...

Easy way to eliminate empty elements following a class using jQuery

I'm encountering a situation where I have a group of elements following a specific class that are either empty or contain only white space. <div class="post-content"> <div class="slider-1-smart"> --- slider contents --- < ...

Validate that the input is an array

Looking for a way to determine if a function parameter is an array or not, and then process it accordingly. If the parameter is not an array, convert it into an array before performing the desired function. For example: interface employee { first: st ...

Strategies for managing Shopify's API request restrictions with the microapps Node.js module

I've been struggling to find a solution to this problem and I just can't seem to get it right. I'm currently using a Node.js module for the Shopify API created by microapps. In my JSON object, I have a list of product IDs and SKUs that need ...