"Opt for a choice that does not rely on a specific

Encountering an issue with a select menu and its model. In this scenario, usaStates represents an object array saved in the root scope.

<label>State:</label>
<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities()">
    <option>Select a state</option>
</select>

Within my controller:

$scope.selectedState = null;
$scope.getCities = function()
{
   console.log($scope.selectedState);
   var stateCode = $scope.selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

Upon selecting a state, the getCities function is triggered, however $scope.selectedState remains null. This code functions correctly in other views. Any suggestions as to why it might not be working here?

UPDATE The source of my states is:

[{id: "AL", name: "Alabama"}, {id: "AK", name: "Alaska"}, {id: "AZ", name: "Arizona"},…]

Answer №1

It's possible that the model value is not being properly updated and the ng-change event is triggered prematurely.

One way to resolve this issue is by passing it as a parameter.

<select name="state" ng-model="selectedState" ng-options="state.name for state in usaStates" required ng-change="getCities(selectedState)">
    <option>Select a state</option>
</select>

In your controller:

$scope.selectedState = null;
$scope.getCities = function(selectedState)
{
   console.log(selectedState);
   var stateCode = selectedState.id;
   MainService.getCities(stateCode)
   .then(function(httpData){
      $scope.cities = httpData.data;
   })
   .catch(function(error){
      console.log(error);
   });
};

Answer №2

Consider passing the selectedState variable to the function getCities(selectedState).

For example:

HTML

<select name="state"
        ng-model="selectedState" 
        ng-options="state.name for state in usaStates" 
        ng-change="getCities(selectedState)"
        required="required">
    <option>Select a state</option>
</select>

Javascript

$scope.selectedState = null;
$scope.getCities = function(selectedState) {
    $scope.selectedState = selectedState;
    console.log($scope.selectedState);
    var stateCode = $scope.selectedState.id;
    MainService.getCities(stateCode)
            .then(function(httpData) {
                $scope.cities = httpData.data;
            })
            .catch(function(error) {
                console.log(error);
            });
};

I hope this explanation is useful.

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

Prevent ui-select from being highlighted when clicked

here's a dilemma : (all in angular 1) I'm using a ui-select like this : https://i.stack.imgur.com/RzH2u.png Here's the code snippet : <div class="formZone-group"> <div class="mandatory-fl"> <div class="man ...

Tips for formatting angular text sections

Within the scope of a controller, I have a status variable. After a successful rest PUT request, I add a message to this JavaScript variable. This message is displayed in my template using the {{status}} Is there a way to customize the styling of this mes ...

How can I update a CSS class value by utilizing AngularJS variables?

I am currently facing an issue with making my CSS values dynamic. The code I have tried is not functioning as expected. <style> .panel-primary { background-color:{{myColorPanel}} } </style> I came across a similar query on Ho ...

Implementing automatic activation of a tab upon page load using Angular

I am currently working with a set of Bootstrap nav pills in my navigation bar. The 'ng-init' code in my Angular script sets the 'dateState' to 'past' on page load. However, I have noticed that the 'Past Events' nav p ...

Incorporate dynamic body color changes across all pages using AngularJS

On the home page, I want to change the color scheme so that it is consistent across all pages. The user should be able to choose a color from a list on the home page and have it apply to every page. Currently, the color selection only applies to the home p ...

Enhancing websites with font-awesome icons and upgrading from older versions to the latest

Seeking guidance on updating our project to use the latest Macadmine theme. The transition from Font Awesome 3 to Font Awesome 4 requires changing all icons to their proper names. I came across a helpful resource at https://github.com/FortAwesome/Font-Aw ...

Is it possible to move a directive within a limited parent element?

Is there a way to limit the movement of an angular.js drag directive within the confines of its parent element? You can see the problem I'm facing in this jsbin: http://jsbin.com/maxife/3/edit?html,css,js,output ...

Angular UI grid: Arranging numbers in a straight line at the decimal point

I am interested in aligning decimal numbers in Angular UI Grid as shown below. 11.293 .89 233424 .34345 I have considered different approaches such as using a cell template with aligned divs or transparent 0s. Has anyone successfully imp ...

The Angulajrjs popup timepicker is not located within the input row

Currently, I am working on creating a popup timepicker within a modal. My main goal is to have the button inside the input field rather than after it. Does anyone know how I can achieve this? Thank you. If you need more context, you can check out my plun ...

Deactivate click events in the container div

Here is the html code snippet that I am working with: <div class="parent" ng-click="ParentClick()"> . . . <div class="child" ng-click="ChildClick()"> Some Text </div> </div> When clicking on Som ...

How can I adjust the height of an iframe dynamically using AngularJS?

I wrote a function that resizes the height of an iframe element to always be 100% after it loads: app.directive('iframeAutoSize', [function() { return { restrict: 'A', link: function(scope, element, attrs) { ...

Changing the background color of the legend text when hovering over a d3 doughnut chart

I have a doughnut chart that displays values on mouse hover. However, I would like to change the background of the legend text when hovering over the respective area of the doughnut chart. return { restrict: 'E', scope: { values: ...

What is the CSS method for altering the color of a slider's runnable track upon selection?

Seeking assistance in changing the slider track color upon selection. Struggling to achieve the desired outcome of altering the color as it slides. CSS: /* Custom Styles */ .text-size-slider { line-height: 100%; font-size: 14px; position: relative ...

What is the best way to center align and add an icon to the header in Ionic?

How can I center align an "ion-ios-arrow-up" icon in the header of my Ionic app, similar to the concept shown below? This is my HTML template: <ion-view cache-view="false" view-title="Historical HPP"> <ion-nav-bar class="nav-title-slide-ios7 ...

Tips for deleting Material Angular CSS codes from the head section of your website

I am currently studying AngularJS and Material Angular Design. However, I have noticed that the Material Design includes CSS codes within the <head> tags. See attached screenshot for reference. Is there a way for me to extract these codes from the h ...

Ways to deactivate a button using CSS

I need to use Javascript to disable a link based on its id. By default, the link is invisible. I will only enable the link when the specific id value comes from the backend. HTML <li id="viewroleId" style="display: none;"> <a href="viewrole" ...

Displaying various charts in a single view without the need for scrolling in HTML

How can I display the first chart larger and all subsequent charts together in one window without requiring scrolling? This will eventually be viewed on a larger screen where everything will fit perfectly. Any recommendations on how to achieve this? Here ...

Using a pseudo-element after to center CSS content

Although there are numerous posts discussing this topic, my situation is unique. In my case, I have a collection of colors represented by circles. When I click on a circle, I add content in the form of a check mark by including a class selector with an af ...

Adjust the class based on the model's value in AngularJS

items = {'apple', 'banana', 'lemon', 'cat', 'dog', 'monkey', 'tom', 'john', 'baby'} html <div class="variable" ng-repeat="item in items">{{item}} </div> ...

Where can I locate a specific child element in this scenario?

Currently, I am exploring the possibilities of integrating AngularJS into my application and have encountered a question regarding the click event implementation. Within my HTML code: <div ng-click='clickMe()' ng-controller='testCtrl&ap ...