AngularJS ng-Model not refreshing the list

Currently, I am in the process of developing a web application where the user is required to select an option from the first drop-down list. Upon selecting an option from this list, a second drop-down list loads with data that is dependent on the selection made in the first drop-down. If the second drop-down list contains only one item, the ng-model gets updated accordingly. However, if there are multiple items in the second drop-down, the ng-model does not get updated and always displays the last item selected.

For reference, here is the link to the code on Jsbin: Jsbin link

<body ng-app="starter">

<div ng-controller="MyCtrl">
 <div> Map Type<select ng-model="Map.TypeSel" ng-options="item as item.Name for item in Map.Types track by item.Id" ng-init="Map.TypeSel=Map.Types[0]"></select></div>
 <div>Commodity<select ng-model="Map.MapSel" ng-options="item as item.Metal for item in Map.Cord[Map.TypeSel.Code] track by item.Dim" ng-init="Map.MapSel=Map.Cord[Map.TypeSel.Code][0]" ng-change="loadMap()"></div>
</div>

<script>
var app=angular.module('starter', []);

app.controller('MyCtrl', function ($scope) {
    $scope.Map = [];
    $scope.Map.Cord = [];

    $scope.Map.Types = [{ Name: "Geology", Id: 0, Code: "Geo" }, { Name: "Metallic", Id: 1, Code: "Met" }, { Name: "Non Metallic", Id: 2, Code: "Non" }, { Name: "Rare Earth", Id: 3, Code: "Ear" }, { Name: "Metallic & Non Metallic", Id: 4, Code: "MNe" }];
    $scope.Map.Cord.Geo = [{ "Metal": "Geology Of Oman", "Dim": "2481,3509", "Path": "img/M/GEOLOGY_OF_OMAN.jpg" }];
    $scope.Map.Cord.Met = [{ "Metal": "CHROMITE", "Dim": "2481,3509", "Path": "img/M/Metallic/CHROMITE(M).jpg" }, { "Metal": "COPPER", "Dim": "2481,3509","Path":"img/M/Metallic/COPPER(M).jpg" }, { "Metal": "GOLD", "Dim": "2481,3509","Path":"img/M/Metallic/GOLD(M).jpg" }, { "Metal": "IRON", "Dim": "2481,3509","Path":"img/M/Metallic/IRON(M).jpg" }];
    $scope.Map.Cord.Non = [{ "Metal": "ASBESTOS", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/ASBESTOS(NM).jpg" }, { "Metal": "BARITE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/BARITE(NM).jpg" }, { "Metal": "CLAY", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/CLAY(NM).jpg" }, { "Metal": "GYPSUM", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/GYPSUM(NM).jpg" }, { "Metal": "KAOLIN", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/KAOLIN(NM).jpg" }, { "Metal": "LATERITE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/LATERITE(NM).jpg" }, { "Metal": "LEAD", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/LEAD(NM).jpg" }, { "Metal": "LIMESTONE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/LIMESTONE(NM).jpg" }, { "Metal": "ORNAMENTAL STONE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/ORNAMENTAL_STONE(NM).jpg" }, { "Metal": "PHOSPHATE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/PHOSPHATE(NM).jpg" }, { "Metal": "PYRITE", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/PYRITE(NM).jpg" }, { "Metal": "SILICA", "Dim": "2481,3509", "Path": "img/M/NON_Metallic/SILICA(NM).jpg" }];
    $scope.Map.Cord.Ear = [{ "Metal": "STRONTIUM", "Dim": "2481,3509", "Path": "img/M/RARE_Earth/STRONTIUM(RE).jpg" }, { "Metal": "URANIUM", "Dim": "2481,3509", "Path": "img/M/RARE_Earth/URANIUM(RE).jpg" }];
    $scope.Map.Cord.MNe = [{ "Metal": "Metalic & Non Metalic", "Dim": "2481,3509", "Path": "img/M/M&NM.jpg" }];

    $scope.loadMap = function () {        
            console.log($scope.Map.MapSel);

    }

});
</script>

Can someone please provide guidance on what might be the issue with my code?

Answer №1

What if we set the default value to load on ng-change of the initial dropdown

  $scope.loadDefaultValue = function() {
    $scope.Map.TypeSel = $scope.Map.Types[0];
    $scope.Map.MapSel = $scope.Map.Cord[$scope.Map.TypeSel.Code][0];
  }

  $scope.loadSecondDefault = function(typeSel) {
    $scope.Map.MapSel = $scope.Map.Cord[typeSel.Code][0];
  }

var app = angular.module('starter', []);

app.controller('MyCtrl', function($scope) {
  $scope.Map = [];
  $scope.Map.Cord = [];

  $scope.Map.Types = [{
    Name: "Geology",
    Id: 0,
    Code: "Geo"
  }, {
    Name: "Metallic",
    Id: 1,
    Code: "Met"
  }, {
    Name: "Non Metallic",
    Id: 2,
    Code: "Non"
  }, {
    Name: "Rare Earth",
    Id: 3,
    Code: "Ear"
  }, {
    Name: "Metallic & Non Metallic",
    Id: 4,
    Code: "MNe"
  }];
  ...

  $scope.loadMap = function() {
    console.log($scope.Map.MapSel);
  }

  $scope.loadDefaultValue = function() {
    $scope.Map.TypeSel = $scope.Map.Types[0];
    $scope.Map.MapSel = $scope.Map.Cord[$scope.Map.TypeSel.Code][0];
  }

  $scope.loadSecondDefault = function(typeSel) {
    $scope.Map.MapSel = $scope.Map.Cord[typeSel.Code][0];
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="starter" ng-controller="MyCtrl">
    <div>
    <label>TYPE:{{Map.TypeSel}}</label>
    <br>
    <label>MAP:{{Map.MapSel}}</label>
  </div>
  <div>Map Type
    <select ng-model="Map.TypeSel" ng-options="item as item.Name for item in Map.Types track by item.Id" ng-init="loadDefaultValue()" ng-change="loadSecondDefault(Map.TypeSel)"></select>
  </div>
  <div>Commodity
    <select ng-model="Map.MapSel" ng-options="item as item.Metal for item in Map.Cord[Map.TypeSel.Code]" ng-change="loadMap()">
  </div>
</div>

NOTE: The 'track by Dim' has been removed because it does not have a unique value

Answer №2

Ensure that the value of Dim is unique when using track by item.Dim. Currently, all items have the same Dim value, resulting in only the last element being displayed in ng-Model.

For a demonstration of this concept, please refer to this Working Plunkr

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

Instructions for incorporating highcharts sub modules into a React application

I have been utilizing the react-jsx-highcharts library to seamlessly integrate Highcharts into my React application. Everything is functioning perfectly. However, I am now interested in incorporating the boost module. I attempted to add it by simply using ...

Ways to access information received from AngularJS in a different Javascript file

I am currently using Angular to retrieve output from a controller and display it using ng-bind. However, I have another separate JavaScript file that needs to utilize a value returned from Angular. In the example code provided below, the TestAppCtrl is ca ...

Utilizing Google Maps to generate outcomes for an online platform

My approach with Google Maps is a bit unconventional. Instead of rendering images, I aim to execute JavaScript code that processes data and returns a text response. However, I soon realized that running JavaScript as a remote web service might not be pos ...

Styling and Script Files on a JQuery Mobile Website

Is it necessary to include CSS and JS files in every HTML page for a mobile site developed with JQueryMobile? <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" /> <script src="http://code.jquery.com/jqu ...

Determine the total count of files in queue with Uploadify prior to initiating the upload process

When I specify auto: false in the uploadify settings, the upload process will only start when the submit button is clicked. Once the onQueueComplete event is triggered, the form will be submitted. However, if no files are selected, the onQueueComplete even ...

What is the best way to smoothly scroll to another page using a specific id?

My website consists of multiple pages and I am looking for a code that will allow for smooth scrolling navigation to another page when loading on a specific id or section. For example, in the navbar I have multiple pages with links. When clicking on a lin ...

Ensuring the next tab is not accessible until all fields in the current tab are filled

I am working on a form with a series of questions displayed one at a time, like a slide show. I need help with preventing the user from moving to the next set of questions if there is an empty field in the current set. Below is the script I am using to nav ...

The state is not updating in a timely manner

After clicking submit in the form, I only receive results upon a second press. When debugging, it appears that setState is updating the state only on the second attempt (userId), but I want it to wait until the state is fully updated (so userId will refl ...

Tips for automatically incorporating animation upon page initialization

I'm looking to add an automatic image effect when the page is loaded. I currently have this code in my js file: $(window).ready(function(){ $(pin).click(function(){ $("#pin01").show().animate({left: '650px'}); }) }); Here is the HTML wit ...

Display the corresponding div when the span class is updated

If I have two span elements with class "selected" changing width based on selection, I just need to determine when span2 is selected. <span class="swatch swatch-image span1"> <span class="swatch swatch-image span2 selected ...

What is the reason behind State's disappearance only after a variable has been assigned to

Currently, I am working on a file gallery with a straightforward setup. The gallery consists of a master component and two sub-components. In the image preview section, there are left and right arrows that trigger a function named "clickHandler." This func ...

Display HTML content retrieved from a string saved in a React database

I am currently in the process of creating a React page and facing a challenge with incorporating HTML content from a RTDB that has been styled using "use styles". Here is an example of the styling: import { makeStyles } from '@material-ui/core/style ...

Calculate the total number of table rows added using jQuery

I am seeking help to identify the error in my code. My goal is to count the number of table rows added by the end user and display an alert box if the row count is not equal to 2. Below is my HTML code: <table width="100%" border="0" cellspacing="0" c ...

Views for registering with Ionic

I am in the process of developing a registration view, but I am encountering an issue with the checking statement to determine if the user is already registered. This check currently occurs within $ionicPlatform.ready as shown below: $ionicPlatform.ready( ...

Working with SASS imports in an isomorphic React app: best practices

Currently, my React app is set up with SSR support as follows: React app Express server that compiles the React app using webpack Using babel-node to run the Express app with ES6 features Everything works fine until I added CSS modules to the React app, ...

Animation is not applied to Bootstrap Collapse on a row within a table

My Bootstrap 4 table has an issue - when I apply the "collapse" class to a table row, it behaves differently compared to applying it to a div element. Clicking "animate div" smoothly animates the target div, but clicking "animate tr" does not animate the ...

Overlaying images with cropped elements

When uploading an image on a webpage, I want to display a preview of the image. I am looking to create an overlay that showcases the image in a rectangle at the center, surrounded by a semi-transparent background outside the rectangle. Something resemblin ...

I am looking for a custom script for a splash page that will automatically redirect users to one of three designated pages based on the information stored

As a programmer, I'm well-versed in coding but lack knowledge about creating and utilizing cookies. If anyone could provide guidance on this matter, it would be highly appreciated. I believe I require two concise scripts for this task. 1st Script: T ...

Trying to draw a comparison between a text box and an individual element within

I am having some difficulty comparing user-entered text in a textbox with an element in an array. function checkUserInput() { var str = imageArray[randomNumber]; var index = str.indexOf(document.getElementById('textBox').value); ...

Discovering elements that are shallower than a chosen selector

I'm currently developing a jQuery plugin designed to facilitate the management of form collections. This plugin is intended to incorporate buttons for adding, removing, moving up, and moving down within the collection. In every collection's r ...