The array bound to the model is not in sync with the AngularJS select directive

My task involves creating a basic select directive using angularjs.

However, I am facing an issue where the options in the select directive appear out of order.

The directive is meant to provide numeric options up to 100. I initialize an array using a loop when my controller is initialized and then add it to the model.

 var init2 = 1;
 var percentageAmount = [];
 while(init2 != 100) {
     var current = {value:init2, id:init2};
     percentageAmount[init2] = current;
     init2++;
 }
 $scope.percentageAmounts = percentageAmount;
 $scope.percentageAmount = 1;

I proceed to bind this array in the template.

Percentage Amount:

<select ng-model="$parent.percentageAmount" name="percentage-amount" id="percentage-amount" ng-options="value.id as value.value for (key,value) in $parent.percentageAmounts" required>
</select>

Upon inspection, I notice that the options are not displayed in the correct order in the DOM. It seems like they're being grouped alphabetically (with numbers being treated as high values).

This discrepancy puzzles me because I have previously created arrays with non-numeric data and bound them to select directives, and in those cases, the options always appeared in the same order as the array itself.

Category:
<select ng-model="couponCategory" name="coupon-category" id="coupon-category" ng-options="value.id as value.value for (key,value) in couponCategories" required>
</select>

Here is the logic used to build the array for the last select directive:

$scope.couponCategories = [{value:"Whole Order", id:"Whole Order"},{value:"Per Item", id:"Per Item"},{value:"Per Item Quantity", id:"Per Item Quantity"},{value:"In A Category", id:"In A Category"}];

I have tried converting all values in the array to integer-based strings (both on the id, the value, and both)

If anyone else has encountered this issue and found a resolution, I would greatly appreciate your help.

Answer №1

The reason for this occurrence is that the array is being treated as an object, causing the numeric indices to be seen as string property names of the object.

Angular perceives it as an object due to the ngOptions format you are using:

... for (key, value) in ...

To inform Angular that it is an array, you can modify it like so:

<select ... ng-options="amount.id as amount.value for amount in percentageAmounts">
</select>

Additionally, check out this brief demonstration.

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

What are the best techniques for showcasing rich text content in vue.js?

I'm working on a web application and attempting to showcase uploaded rich text content using vue.js. The content is generated by Action Text in the following format. <h1>text</h1><div>sample text<br><action-text-attachment ...

Navigate to the following section by scrolling down, and return to the previous section by scrolling up

Currently, I am working on a portfolio website for a filmmaker and I have a specific requirement. As users scroll down the window, I want the page to smoothly transition to the next section, and when scrolling up, I want it to go back to the previous secti ...

Develop an AJAX script for processing multiple form inputs in PHP and HTML

I am working on a code that involves multiple form submissions, but the submit functionality is not working due to having multiple submits on one page. I have realized that I need an Ajax script to handle this, but I am new to it. Can someone provide me wi ...

TinyMCE: Tips for adding and highlighting text in your content!

Is there a way to insert, or even replace the current selection with some content and then have it automatically selected? Take for instance this text: Hello nice world! The user has selected nice. After clicking a button, this code is executed: editor. ...

Tips for accessing the selected button in notification.confirm() within a PhoneGap app

Recently, I implemented the Phonegap notification.confirm in this way: navigator.notification.confirm( 'Do you wish to proceed?', function() { console.log("Function Called"); }, 'Game Over', 'Continu ...

What causes the [$parse:syntax] error when I tap on the arrow icon within Google Maps?

.controller('MapCtrl', [ '$scope', '$http', '$location', '$window', function ($scope, $http, $location, $window) { $http.get('****').success(function (data, dealers, response) { ...

Linking controller scope to service characteristics

Recently, I have been exploring the utilization of services within controllers and specifically binding scope properties on a controller to properties in a service. In reviewing the code snippet below, I noticed that the $scope.stockCountProp in my contro ...

Techniques for utilizing ng-class to merge class attributes

I'm new to Angular and I want to combine classes using ng-class. Specifically, I'd like to use the save class along with the firstClass class if something = First. I've been doing some research on how to implement this with ng-class but I ha ...

Create names for links using jQuery based on the data received from an AJAX response

I am currently utilizing the jQuery UI tooltip script available at this link. As a result, I have tooltip links with varying "data-id" attributes like so: <a tooltip-link data-id="12555"></a> <a tooltip-link data-id="38"& ...

What is the best way to show a table with 100% width in the Chrome browser?

I am currently working on debugging and expanding an express application that showcases a dataset through a series of nested tables on a webpage. Initially, all the CSS resided within style tags in the head section of the HTML file, and the tables were dis ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Differences between using CSS properties and AngularJS filters:CSS properties

When working on an angularjs application, one task may be to convert a string to uppercase. There are 2 options available to achieve this, both yielding the same result. However, it is important to consider the scenarios in which one option may be preferre ...

Place a gap at a specific spot within the boundary line

Here is a CSS code snippet that displays a horizontal line: .horizontalLineBottom { border-bottom:solid #6E6A6B; border-width:1px; } Is it possible to add space at a specific position on this line? For example, _________________________________ ...

Broadcast to every socket except the one that is malfunctioning on Socket.io

My current task involves sending a message to all connected sockets on my server using socket.io. The code I have written so far looks like this: if(electionExists) { var connectedClients = io.sockets.adapter.rooms[electionRequested].sockets; ...

Struggling with repeatedly traversing characters in a string to solve the Palindrome challenge

I am working on a recursive solution for a Palindrome problem, but it seems that my code is only considering the first recursive call instead of the second one which should analyze all characters in the string. I suspect there might be a logical error in ...

What is the best way to declare strings within a Typescript interface?

I have an array of Projects with multiple strings in the stack property const projects: IProject[] = [ {name: '', description: '', stack: {'php', 'sql'}} ] What is the best approach for defining the interface? ...

Utilizing jQuery or JavaScript to transfer information within a Bootstrap modal

I am working with a table that is generated from an SQL Table using PHP for data looping. HTML <tbody> <?php $no = 1; foreach($data_request as $data) { ?> <tr> <td class="center"><?php echo $no++.". ";?> ...

Tools needed for Angular project development

Currently, I am engaged in a project using AngularJS on a Windows 7 computer. My desire is to be able to seamlessly transition between working at the office and working from home or any other location. If I have everything installed in a folder named C:/C ...

The Google Maps JavaScript API is displaying a map of China instead of the intended location

After multiple attempts, I am still facing an issue with setting up the Google Map on my website. Despite inputting different coordinates, it consistently shows a location in China instead of the intended one. Here is the code snippet that I have been usin ...

Is there a way to successfully transfer both the event and props together?

For simplifying my code, I created a function that triggers another desired function when the Enter key is pressed. Here's an example of how it works: const handleKeyDown = (event) => { if (event.key === 'Enter') { event.preventDefa ...