What could be the reason for the malfunctioning of the Angular options tracking by ID feature?

I seem to be facing an issue with my code:

There is an object that holds the id of an item, along with an array containing these items. I require a 'select' element to display the currently selected item and allow for changing the selection.

The model of the 'select' has been set to object.selectId. The ng-options for the 'select' are "option.Text for option in options track by optionId".

However, there seems to be a mismatch between the model and the types of 'select' options.

Could you please guide me on achieving the desired outcome?

Here's a fiddle demonstrating what I am trying to do: https://jsfiddle.net/vb2xe1mc/5/

Code:

<script>
angular.module('myApp', [])
  .controller('myctrl', ['$scope', function($scope) {

    $scope.item = {
      id: 1
    };
    $scope.options = [
      {Text: "zero",  Id: 0}, 
      {Text: "one",   Id: 1}, 
      {Text: "two",   Id: 2}, 
      {Text: "three", Id: 3}
    ];

    $scope.selectChange = function() {
      alert($scope.item.id);
    };
  }]);
</script>
<div ng-app="myApp">
   <div ng-controller="myctrl">
       <select ng-model="item.id" ng-options="option.Text for option in options track by option.Id" ng-change='selectChange()'>
       </select>
   </div>
</div>

If possible, kindly point out any errors in my approach or correct the fiddle.

Thank you ^_^ Andy

Clarification: The existing selected item in the model has id 1. I would like the list to automatically preselect the option with id 1 in this scenario. Furthermore, when an option is selected, it should update the item.id with an integer value instead of the entire option item. It should specifically set item.id to the option's Id.

Answer №1

<select ng-model="selectedItem.id" ng-options="opt.id as opt.Name for opt in choices" ng-change='onSelectChange()'>

Ensure you are selecting opt.id instead of just opt, and there is no need to use track by.

Answer №2

Link the select to ng-model="item", not ng-model="item.id".

Make a final decision on whether to use id or Id

<div ng-app="myApp">
  <div ng-controller="myctrl">
    <select ng-model="item" ng-options="option.Text for option in options track by option.Id" ng-change='selectChange()'>
    </select>
  </div>
</div>


angular.module('myApp', [])
  .controller('myctrl', ['$scope', function($scope) {

    $scope.item = {
      Id: 1
    };
    $scope.options = [{
      Text: "zero",
      Id: 0
    }, {
      Text: "one",
      Id: 1
    }, {
      Text: "two",
      Id: 2
    }, {
      Text: "three",
      Id: 3
    }, ];

    $scope.selectChange = function() {
    console.log ($scope.item.Id)
      alert($scope.item.Id);
    };
  }]);

To view a corrected version, click here: https://jsfiddle.net/ax3k418p/

Answer №3

Click here to view the solution on JSFiddle

To make this work, ensure that you bind item to ng-model. Initially set $scope.Id to 1, not $scope.id = 1.

Remember to use alert($scope.item.Id); when alerting.

<div ng-app="myApp">
  <div ng-controller="myctrl">
    <select ng-model="item" ng-options="option.Text for option in options" ng-change='selectChange()'>
    </select>
  </div>
</div>

JS:

angular.module('myApp', [])
  .controller('myctrl', ['$scope', function($scope) {

    $scope.item = {
      Id: 1
    };
    $scope.options = [{
      Text: "zero",
      Id: 0
    }, {
      Text: "one",
      Id: 1
    }, {
      Text: "two",
      Id: 2
    }, {
      Text: "three",
      Id: 3
    }];

    $scope.selectChange = function() {
      alert($scope.item.Id);
    };
  }]);

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

extracting data from JSON and storing it in an array

JSON: var res = { "response": { "data": { "profilesearchsnippet": [ [ { "profileInfo": { "firstname": "Sundar", ...

What's Next? Redirecting Pages in Node.js Express after Handling POST Requests

Is it possible to redirect to a different page from a post request? module.exports = function(app) { app.post('/createStation', function(request, response){ response.redirect('/'); //I'm having trouble getting ...

Efficiently Loading JavaScript Files in Django for Optimal Website Performance

I have a Django blog app with a Post model that includes a field called body. This field may contain Latex, so I utilize MathJax.js, as well as code snippets, for which I use highlight.js. Sometimes I use both, and other times neither. Is there a way to a ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...

How can I access a PHP variable from an external .php file within a JavaScript script?

I have recently implemented a JavaScript code called "upload.js" for uploading files to my server: function beginUpload(){ document.getElementById('upload_form').style.visibility = 'hidden'; return true; } function endUpload(s ...

Add a trash can or delete icon within every row of a table using Vue.js

I am new to vue.js and I'm struggling to implement a trash icon in each row of a table for deleting rows. Additionally, I'm trying to make the input of a cell act as a dropdown menu or list within the table rows. I recently came across this scrip ...

JS: delay onClick function execution until a page refresh occurs

Currently, I am working on a WordPress site that involves a form submission process. Upon successful submission, a new post is created. After the user submits the form, I have implemented JavaScript to prompt them to share a tweet with dynamically prepopu ...

Remove specific data from jQuery datatables using data attribute

My jQuery datatable is loaded with data from a database without any filtering by default, providing all the necessary information for users. In addition to the built-in search functionality of jQuery datatables, I have incorporated custom search input fiel ...

Launching the ngx Modal following an Angular HTTP request

Trying to trigger the opening of a modal window from an Angular application after making an HTTP call can be tricky. Below is the content of app.module.ts import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/pla ...

Update the appearance of Morris Donut following an AJAX request

Currently, I am implementing Morris Donut for a dashboard project and using AJAX to fetch data with two date ranges as parameters. However, I am encountering an issue where entering new date ranges results in rendering a new Donut Chart on top of the exist ...

Challenges with pjax/ajax and handling the browser's back button

I've implemented pjax to ajaxify my menu links, which works well until I encounter an issue with the browser back button. In my JavaScript file, I have both Common Script files (to load all necessary js files when the user hits the URL) and Script fil ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

The functionality of the Wordpress editor is impaired when the parent element is set to display:none during rendering

My goal is to create a popup window with text fields and a wp_editor. The content is already rendered in the footer but only set to display none. I have made attempts at implementing this, however, they are not working perfectly. Each approach has its own ...

Using Angular's async, you can retrieve a value returned by a promise

Within the library I am currently utilizing, there is a method called getToken which can be seen in the following example: getApplicationToken() { window.FirebasePlugin.getToken(function(token) { console.log('Received FCM token: ' + to ...

Exploring the process of integrating absolute paths within a global SCSS file in a VueJS project

The webpack configuration in my vue.config.js file looks like this: const path = require("path"); module.exports = { pluginOptions: { 'style-resources-loader': { preProcessor: 'scss', patterns: [ "./src/style ...

Select multiple rows by checking the checkboxes and select a single row by clicking on it in the MUI DataGrid

I am currently utilizing the MUI DataGrid version 4 component. The desired functionalities are as follows: Allow multiple selections from the checkbox in the Data Grid (if the user selects multiple rows using the checkbox). Prevent multiple selections fr ...

Searching the Google Place API to generate a response for dialogflow

I am currently facing an issue while trying to utilize the Google Place API for retrieving details to display a map (by fetching coordinates) and location information (address) as a response from my chatbot. I have created this code snippet, but encounteri ...

Attempting to simulate the behavior of nfcManager by utilizing the nfcManager.start() function in react native testing library

In the process of developing my Android app, I encountered a need to read NFC tags. To accomplish this task, I decided to utilize the react-native-nfc-manager library. However, during my implementation, I faced two perplexing issues that have left me stump ...

I am unable to implement v-bind click within a v-for loop

While working with VueJS framework v-for, I encountered a problem when trying to loop through lists of items. Each item index was supposed to be assigned to a variable, but the v-bind click event wasn't being attached properly inside the v-for element ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...