When utilizing track by in ng-options, the selectbox value fails to update accordingly

Using track by in ng-options causes Angular to not update the selectbox value immediately, even after a selection is made. It seems to work correctly on the second try, even when the model value is already set.

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.items = [
        ['ali', 'ali']
    ];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        value: {{selected}} <br><br>
        <select 
            ng-options="item[0] as item[1] for item in items track by item[0]"
            ng-model="selected"></select>
  </fieldset>
</div>

Answer №1

The solution can be found in the documentation (https://docs.angularjs.org/api/ng/directive/ngOptions - refer to the section "select as and track by")

It appears that combining track by with certain select as expressions may not work.

However, a workaround is to use

ng-options="item as item[1] for item in items track by item[0]"
instead of
ng-options="item[0] as item[1] for item in items track by item[0]"

Check out this example: https://jsfiddle.net/b9upojmb/1/

Answer №2

Using track by in AngularJS is intended for objects, not array elements. It is recommended to use objects instead of arrays. Here is an example:

var myapp = angular.module('myapp', []);
myapp.controller('FirstCtrl', function ($scope) {
    $scope.items = [
        { id :1, value : 'ali'},
        { id :2, value : 'ahmed'}
    ];
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app="myapp">
    <fieldset ng-controller="FirstCtrl">
        value: {{selected}} <br><br>
        <select 
            ng-options="item as item.value for item in items track by item.id"
            ng-model="selected"></select>
  </fieldset>
</div>

Answer №3

When using the track by feature in AngularJS, make sure to pass an array of objects so that you can track by any object properties.

var myapp = angular.module('myapp', []);
myapp.controller('SecondCtrl', function ($scope) {
$scope.items = [
                    { name : "carol" },
                    { name : "dave" },
                    { name : "emma" }
               ]

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.js"></script>
<div ng-app="myapp">
    <fieldset ng-controller="SecondCtrl">
        value: {{selected}} <br><br>
        <select 
            ng-options="item as item.name for item in items track by item.name"
            ng-model="selected"></select>
  </fieldset>
</div>

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

Tips for implementing data-autoload, data-origin, and data-callback script tags in Angular with typescript

I am facing an issue while trying to insert my script into an Angular application using the 'data-autoload', 'data-origin', and 'data-callback' keys. When I attempted to create the script element using '_renderer2.createE ...

Attempting to showcase the information in my customized SharePoint Online list through a Web Part Page utilizing AngularJS

<script> //AngularJS Code goes here var appVar = angular.module('listApp', ['ngRoute']); appVar.controller("controller1", function($scope){}); function FetchEmployeeData($scope, EmployeeList){ var reque ...

Solution for problem with IE scrollWidth

Encountered a peculiar bug in IE where the scrollWidth is consistently off by 1px compared to the offsetWidth. This anomaly appears to be triggered by the length of text/characters within the element, specifically when overflow is set to something other th ...

The function is receiving an empty array of objects

This code is for an Ionic app written in typescript: let fileNames: any[] = []; fileNames = this.getFileNames("wildlife"); console.log("file names:", fileNames); this.displayFiles(fileNames); The output shows a strange result, as even though there ar ...

Using jQuery to verify the status of every input when the page loads

My jQuery price calculator is missing a feature to check if inputs are selected when the page loads. Currently, it only recognizes that Apple is checked after clicking on Banana. How can I modify it to automatically check all inputs at the start? I attem ...

Retrieving the output from a nested function within a function in a Node.js application connected to a

I'm currently working on a basic web application that interacts with a database by performing INSERT and SELECT operations on a single table. While I have utilized a function from various tutorials, I am struggling to retrieve the results from the SEL ...

Diving into Redux brings up the question of whether to use a generic reducer or a

When working with Redux, what is the preferred approach: Creating entity-specific reducers or utilizing a generic reducer based on strict action keying conventions? The former can result in more boilerplate code but offers loose coupling and greater flexib ...

Incorrect implementation of Bootstrap CSS in Jade template

Currently, I am leveraging Express to construct a website. However, there seems to be an issue with my jade template not displaying the bootstrap grid system accurately. Despite double-checking that my app path is correctly set through app.use(express.stat ...

I am struggling to link my JS application with a PHP file as it is showing "PHP file not found

I am facing an issue with my JS application. I am unable to send data from jQuery to a PHP file, as I encountered this error message: POST https://magazyn.rob-tech.pl/savesettings.php 404 The app is running on PORT=8080 npm run start and the package.json ...

Tips for preventing unstyled content flash when updating CSS files dynamically

The following jQuery function is used to replace CSS files: function UpdateTheme(theme) { var links = $("link"); var _t = theme; $.each(links, function (i, link) { var _h = $(link).attr('href'); _updatedHr ...

Prevent duplicate submissions by disabling the ASP.NET Forms button after it has been clicked

How can I disable an ASP.NET button after it's clicked to prevent double-clicking, and then enable it again after the submission is complete? I need some assistance with this. ...

Set up a single array containing multiple objects in a table, each with its own unique set of keys

I am currently developing an application that retrieves data from one or multiple databases, each with different names and varying numbers of columns. The goal is to consolidate this data into a single report screen and export it as a table. While the tabl ...

What is the best method for initializing the value of ng-model as an empty string in AngularJS?

I need help setting the initial value for an attribute in my model. Here's the code I'm using: <input type="text" ng-model="selectedModel.title" name="title" value="" > What I want is for the attribute value to be initially set as an empt ...

Making AJAX requests to retrieve data from a JSON database array, then utilizing the CSS visibility property to conceal HTML elements dynamically

As a enthusiastic beginner, I'm facing a challenge that seems to have no easy solution. Can someone please assist me with this: How can I assign all the ids from a JSON database to the variable dotContainer, in order to hide all corresponding HTML id ...

Achieving responsive masonry layout with Bootstrap 4

I'm attempting to implement the bootstrap 4 masonry effect on my website, but I'm facing issues with card responsiveness. The page is very basic without any special effects. While the page works well when resizing the browser window, it doesn&ap ...

Using jQuery to implement tiered radio buttons styled with Bootstrap

I am currently in the process of learning jQuery, so please excuse my lack of knowledge in this area. I am working on a web form using Bootstrap that involves tiered radio buttons. When the user selects "Yes" for the first option, it should display the ne ...

What is the proper method for submitting a mail form via AJAX without using jQuery?

Currently, I am working on integrating a PHP mail form with AJAX. The aim is to create a straightforward form that collects user information such as phone numbers and sends it to my email address. While I have managed to set up the form to send emails usi ...

Puppeteer with Typescript: Encountering issues during the transpilation process

The issue stems from the fact that I am unable to use Javascript directly due to Firebase Functions Node.JS version lacking support for Async/Await. As a workaround, I have converted the code into Typescript and am currently attempting to transpile it to c ...

The variable that was posted is not being successfully transferred within the query

There seems to be an issue with retrieving data from the ajax call in ajaxcall.php and assigning it to $place = $_POST['place']; in listplace.php. Despite this problem, the code runs smoothly otherwise. I've tried numerous times to get the ...

Console log showing no response from AJAX request

For my group project, I've been working on setting up an API to display a response in the console log. After troubleshooting and fixing errors, I am still not seeing any response when I click submit. JavaScript var zipcode = ""; function localMovie ...