Troubleshooting issues with ng-options not correctly updating ng-model in AngularJS when using ajax requests

I have a question regarding my logic that I can't seem to figure out.

In this Fiddle example, everything works fine without using AJAX or a timeout. However, when I try to implement the same logic with a timeout/ajax, the expected behavior does not occur. Can someone help me understand and fix this issue?

Here is the sample code I am referring to: JS FIDDLE Example

HTML:

<body data-ng-app="appMain">
    <div ng-controller="SearchController">
        <input type="text" ng-model="SearchTerm" />
        <input type="button" value="Submit Search" ng-click="QuerySuggestions()" />
        <select ng-show="ShowSuggestion" name="cmbSelectedSuggestion" ng-model="SelectedSuggestion" ng-options="text as suggestion.Detail for suggestion in SuggestionList" ng-change="WhoIsSelected(suggestion)">
        </select>
    </div>
</body>

AngularJS:

angular.module('appMain',[])
.controller('SearchController',function($scope, $http, $timeout){
  $scope.SearchTerm = '';
  $scope.ShowSuggestion = false;
  $scope.SuggestionList = [];
  $scope.SelectedSuggestion = null;
  $scope.QuerySuggestions = function()
  {
    //Simulating an AJAX request with a 2s delay for response
    $timeout(function(){
      var oJSON = {"List": [
              {
                  "Id": 1,
                  "Type": "State",
                  "Name": "Rio de Janeiro",
                  "Detail": "Rio de Janeiro - State, Brazil"
              }
              ,
              {
                  "Id": 1,
                  "Type": "City",
                  "Name": "Rio de Janeiro",
                  "Detail": "Rio de Janeiro - City, Rio de Janeiro, Brazil"
              }]};

        $scope.SuggestionList = oJSON.List
        $scope.ShowSuggestion = true;
    }, 2000);

  }

  $scope.WhoIsSelected = function($option){
    $scope.WhoIsSelectedFirstApproach();
    $scope.WhoIsSelectedSecondApproach($option);
  }

  $scope.WhoIsSelectedFirstApproach = function(){
    console.log($scope.SelectedSuggestion); //why undefined ?!?!?
  }

  $scope.WhoIsSelectedSecondApproach = function($option){
    console.log($option) //why undefined ?!?!?
  }
})

Answer №1

Remember to always write your ng-options as suggestion.Detail as text, not as text as suggestion.Detail.

Answer №2

After conducting a more thorough search, I was able to successfully resolve the issue and gain a better understanding of my mistakes.

Initially, coming from a T-SQL background, I mistakenly believed that "text" served as an alias for the suggestion.Detail field in the expression

text as suggestion.Detail for suggestion in SuggestionList
. However, this assumption was incorrect. In reality, "text" does not function as an alias; it represents the object or object.field that AngularJS should expose as the ng-model. Therefore, to address this misunderstanding, I needed to update the expression to:
suggestion as suggestion.Detail for suggestion in SuggestionList

ng-options="suggestion as suggestion.Detail for suggestion in SuggestionList"

This adjustment successfully resolved the WhoIsSelectedFirstApproach. Yet, when attempting to pass the object to a function within the ng-change directive, using suggestion in the expression proved ineffective. Recognizing the discrepancy in logic between different ng-* directives, I found a solution by referencing the ng-model field within the ng-change attribute. By adjusting Function(suggestion) to Function(modelField), I effectively addressed this issue:

ng-change="WhoIsSelected(SelectedSuggestion)"

For further details and clarification, please refer to the SOLVED JS FIDDLE

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

Uploading files using Ajax without the need for additional plugins or submitting a form

I have been struggling to find a solution for uploading files via Ajax when the input field is not enclosed within a form tag. I have already attempted this method. This is the HTML snippet: <span id="user-image-up-btn">Upload Image</span> &l ...

Tips on modifying a Vue app's property externallyHere are some techniques on how

I am curious about changing the property of a vue app from an external source. I want to create a new vue app named 'app' and set 'app.propertyName' to 'someValue'. However, my attempt below did not yield the desired outcome. ...

Information backed by the HTML5 Local Storage feature

Is it possible to use a Local Storage object to store another Local Storage object? Thank you in advance. ...

Hover effect for changing image source not functioning as anticipated

I'm having issues creating an image that plays a GIF on hover. I came across some jQuery code on this website that should work, but it's not working for me. Any thoughts on what the problem might be? Here is the HTML and JavaScript code: $(doc ...

Creating a dynamic hyperlink variable that updates based on user input

I am attempting to create a dynamic mailto: link that changes based on user input from a text field and button click. I have successfully achieved this without using the href attribute, but I am encountering issues when trying to set it with the href attr ...

What is the reason behind utilizing the external 'this' within the inner function in Vue: $this=this?

Recently, I came across some code online that included a line $this=this. My initial interpretation was that this line assigns the 'this' of the outer function to a variable, allowing it to be used in the inner function as well. However, upon fur ...

Troubleshooting issue: jQuery/Ajax selector not functioning as expected

After using jQuery.ajax() to fetch HTML content from a PHP source and inject it into an element on the page, I've noticed that jQuery selectors do not work on the elements within that loaded HTML. Is this a common issue or should I provide an example ...

Identifying the JS Tree nodes that have been repositioned via drag-and-drop

I'm working with a JS Tree structure that includes drag and drop functionality. Here's the basic code I have so far: $('#using_html_1').jstree({ "core": { "check_callback":true }, "plugins" : ["dn ...

Encountering a Mixed Content error while attempting to send an AJAX request to a

I'm currently facing a challenge with making an ajax call using jQuery from a secure https page jquery var loadData = function (param1, param2) { return $.getJSON("https://www.domian.com/thing/" + param1 + "/" + param2 + "/", function (data) { ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

Issue with PassportJs not forwarding users after successful authentication

I'm facing some challenges with implementing Passport for authentication. I have set up my signup strategy in the following way: passport.use('local_signup', new localStrategy({ usernameField: 'username', passwordField:&apo ...

Avoiding setting state before useEffect is important to ensure that the component's initial

I have a React/Next component that retrieves data from firebase storage based on the route. For example, if the route is http://localhost:3000/training/javascript, the component will fetch data from the /training/javascript route in firebase storage. // Re ...

Retrieving and storing state in session storage with React

My webpage features a sidenav with expansion panels that can be opened and closed. I am currently working on setting the state to keep track of which expansion panel is open. However, when I click on one of the items in the sidenav, I get redirected to a ...

Encountering an error message stating "Buffer is not defined" while working with gray-matter

Encountering an issue when trying to utilize gray-matter in Angular 9, the error message displayed is: ReferenceError: Buffer is not defined at Object.push../node_modules/gray-matter/lib/utils.js.exports.toBuffer (utils.js:32) at push../node_modul ...

What happens when Google Polymer platform is used without defining _polyfilled?

My attempt at creating a simple example using Google Polymer's platform.js is running into an error message that says: Uncaught TypeError: Cannot read property '_polyfilled' of undefined This is what I'm attempting to achieve: <cur ...

What could be causing the createReadStream function to send a corrupted file?

My current task involves generating a file from a URL using the fs module to my local system. Initially, everything seems successful. However, when attempting to post this file into a group using the createReadStream() function, I encounter an issue where ...

Difficulty in sharing cookies among subdomains

I have successfully stored my visitors' style sheet preference in a cookie, but I am facing an issue with sharing the cookie across subdomains. Even after specifying the domain, the cookie does not seem to be shared. What could be causing this proble ...

Having trouble with my JQuery image slider... Can anyone help troubleshoot what I might have missed?

I am trying to create a simple image slider, but it doesn't seem to be working. I followed a tutorial on YouTube closely, but since I can't compare my code with theirs on a website, I'm having trouble identifying the mistake. Despite followi ...

I'm encountering an issue with my function in Vuejs where it is only going through one loop before breaking out. How can I

I'm attempting to validate all items in the cart and disable the sell button if the item is already in the cart (I have this implemented for other functionalities). It seems like my loop is only iterating once before stopping. Any suggestions on how I ...

The Angular component router-outlet is not recognized as a known element

I have encountered an error message: 'router-outlet' is not a known element: 1. If 'router-outlet' is an Angular component, then verify that it is part of this module. 2. If 'router-outlet' is a Web Component then add ...