Issues with dynamically loading content into a drop-down menu using AngularJS

Hey there, I need some assistance. I have two select fields, one for states and the other for cities. My goal is to dynamically load cities from a JSON generated on the server when the user changes the selected state. Any help would be greatly appreciated.

JavaScript:

var geo = function(app){

app.controller("geoCtrl",function($scope, $http, geoFactory){
   $scope.mcpios = [];
   $scope.dptos = [];

   $scope.$watch('dpto', function (newVal, oldVal) {
       if(!oldVal || !newVal) return;
       if (newVal.id_departamento === oldVal.id_departamento) { return; }

       geoFactory.actMucpios($scope.dpto.id_departamento).success(function(result){
           console.log(result[0]);
           $scope.mcpios = result[0];
      }); 
    }, true);

     geoFactory.get().success( function(result){
            $scope.dptos = result[1];
            $scope.dpto = $scope.dptos[0];
     });
});

app.factory("geoFactory", function($http){

var factory = {};

factory.get = function(){

    return  $http.get("aplicacion/controladores/controlador_geo.php?listar");
 };   

factory.actMucpios = function(id_dpto){

 return $http.get("aplicacion/controladores/controlador_geo.php?listar&id_dpto=" +  id_dpto);

}

return factory;

});

}

HTML:

<select ng-controller="geoCtrl" ng-change="actulizar()" ng-model="dpto" class="col-md-12"  ng-options="dpto.nombre for dpto in dptos"  >
    <option  ng-repeat-start>Seleccione un Departamento</option>
    <option value="{{dpto.id_departamento}}" ng-repeat="dpto in dptos">{{dpto.nombre}}</option>
</select>

<select ng-model="mcpio" class="col-md-12" ng-controller="geoCtrl">
    <option  ng-repeat-start>Seleccione una Ciudad</option>
    <option value="{{mcpio.id}}" ng-repeat="mcpio in mcpios | filter:dpto.id">{{mcpio.nombre}}</option>
</select>

Any assistance you can provide would be much appreciated. Thank you!

Answer №1

I have created a Plunkr demonstration below that replicates the process of calling a service to fetch a list of states. Upon selecting a state, the object will be retrieved; alternatively, you can request the list of states in the $scope.watch statement to obtain the cities and then update the scope collection for the cities. As a result, each time a new state is chosen, the list of cities will dynamically change.

To view the functioning example, please click on this link: http://plnkr.co/edit/ntUblVSSoBzp053GuYvv?p=preview

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

Utilize dynamic tags to implement filters

Currently, I am working on a project where I have a table displaying elements using ng-repeat. My goal is to implement dynamic filters that can be added through tags using ng-tags-input plugin. These tags will serve as the filter criteria for the table dat ...

Determine the hue of a specific location on a geometric surface

I'm currently working with THREE.js for my scene rendering and I have a complex question - how can I retrieve the color of a specific point on a geometry face? When I mention color, it's not just the face or material color that I'm interest ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...

Tips for patiently waiting for an axios request to finish

Within my vuejs application, I am faced with the challenge of initializing an object using data retrieved from an ajax call: let settings = {} api.readConfig().then((config) => { settings = { userStore: new Oidc.WebStorageStateStore(), author ...

Oops! Could not compile due to a syntax error: Invalid assignment expression on the left-hand side

I am currently developing an application that requires me to retrieve data from the backend containing a userdetail object. In my code, I need to set a current accessToken for the userdetail object: useEffect(() => { if (session?.user && ...

Wrapping an anchor tag with a div in Codeigniter

Can a div tag be used inside an anchor function? I have a div with the following CSS: #first{ opacity:0; } Now, I want to include it in my anchor element. Here is the code snippet: <?php if(is_array($databuku)){ echo '<ol>&l ...

What could be causing my Rest API request to malfunction?

Currently, I am working on a Pokedex website as part of my practice to enhance my skills in using API Rest. However, I have encountered some issues with the functionality. When users first enter the site, the API is being called twice unnecessarily. Additi ...

When rendering, DirectionsRenderer replaces the Marker

I'm currently working on implementing a real-time tracking system for customers to track their deliveries. I have succeeded in setting up markers for the destination and pickup locations, as well as a route path towards them. However, I encountered an ...

Tips for using jQuery to adjust HTML attributes based on conditions

I'm still trying to figure out how to assign a different class attribute to an element based on another element's dynamic numberical attribute. Here is the HTML & PHP code I am working with: <?php for($i=1;$i<=$total;$i++){ ?> <a hr ...

Fontawesome is unable to update the class due to the presence of invalid characters in the string

const toggleDarkOrLight = document.getElementsByTagName('i')[0]; var toggled = false; const toggleFunction = () => { if (toggled === false) { toggleDarkOrLight.classList.remove('fa fa-toggle-off'); toggleDarkOrLight.classLi ...

Adjust image size according to the browser's window resize using JQuery

I am trying to make an image resize based on the browser size changes using JQuery. My goal is for the image to scale without losing its aspect ratio or getting cropped. I have incorporated Bootstrap in my HTML structure: <div class="container-fluid" ...

Gather data from a variety of HTML5 video seminars

I am encountering an issue where I have multiple videos and I want to receive events from each of them. However, I am only able to get the event from one video (as tested in Chrome). Why is this happening? Here is the HTML code: <video id="video1" pre ...

Obtaining text from a select list using JQuery instead of retrieving the value

How can I retrieve the value from a select list using jQuery, as it seems to be returning the text within the options instead? Below is my simple code snippet: <select id="myselect"> <option selected="selected">All</option> <op ...

What are the steps to execute a filter operation on a table by utilizing two select box values with jQuery?

I have a challenge with two dropdown menus. One contains names and the other subjects, along with a table displaying information in three columns: name, subject, and marks. I would like to implement a filter based on the selections in these two dropdowns. ...

Prevent automatic scrolling to the top of the page after submitting a form. Remain at the current position on the

After submitting a form, I want to prevent the page from automatically scrolling back up. How can I keep the same position on the page after form submission? <script type="text/javascript"> var frm = $('#form'); frm.submit(function ...

Having trouble with log4js-node in Node.js not recording logs to file?

Not a expert in nodes, this is my first time using log4js-node. I am attempting to log my ERROR logs and any console logs to a file named log_file.log using log4js on a nodejs server running Express. Below is my configuration file: { "replaceConsole": ...

Tips for developing a directive that supplies values for ng-options

I have select elements with the same options throughout the entire app, but they may vary in appearance. For example, selects for a user's birthday (day, month, year). Is it possible to create a directive that can provide values or expressions for ng ...

Prevent an endless loop in Nextjs by properly implementing conditional rendering techniques

I am working on a Next.js application that includes the following page setup: import { useState, useEffect } from 'react'; import axios from 'axios'; import { withRouter } from 'next/router'; import NotFound from '@/page ...

Approach to retrieving data with Nodejs API

Currently, I am working on a project with Node.js and using Express.js. My goal is to retrieve data from a MySQL database, but I encountered the following error: "await is only valid for async function" How can I resolve this issue? Below is the ...

Using RegisterClientScriptBlock function without the need for a form tag

While attempting to troubleshoot why client code was not being rendered on a page injected by a user control, I stumbled upon this interesting link. It seems that a form tag is required for it to function properly (even though Page.RegisterClientScriptBloc ...