Setting value in Angular's ng-repeat directive

Utilizing ng-repeat, I am creating a table with radio buttons. The main goal is to assign each radio button a value based on the position of the object in the original array (before any sorting takes place). However, using $index assigns the position in the ordered array rather than the original one. How can I assign the correct index, which is the original one?

<tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
<td> {{ person.name}}</td>
<td> <input type="radio" name="radio" ng-model="$parent.selectedPerson" value="{{$index}}"/></td>
</tr>

Answer №1

Upon further reflection:

$index is in relation to the current element within the loop. Considering that you are sorting the array, it's important to store a reference to the object itself from the directive (You can utilize person.id, for instance, if there's a unique id for each person).

You have the option to save a reference to the selected individual using ngValue

angular.module('app', []).controller('ctrl', function($scope) { 
  $scope.selected = { person: null };
  $scope.persons = [{id: 1, name: "person1"}, {id: 2, name: "person2"}, {id: 3, name: "person3"}]; 
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <table>
    <tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
      <td> {{ person.name}}</td>
      <td> <input type="radio" name="radio" ng-model="selected.person" ng-value="person"/></td>
    </tr>
  </table>
  
  <hr>
  <p>Selected Person:</p>
  <pre ng-bind="selected.person | json"></pre>
</div>

By incorporating ngValue and storing a reference to the chosen object during the loop, I am unconcerned with the current position of the object because angularjs ensures that the selected person will be accessible in the controller via $scope.selected.person.

If you wish to pre-select a person, replace

$scope.selected = { person: null };

With

$scope.selected = { person: $scope.persons[1] };

Remember to define $scope.persons beforehand! Place this line after declaring the array in your controller. For example:

angular.module('app', []).controller('ctrl', function($scope) { 
  $scope.persons = [{id: 1, name: "3person1"}, {id: 2, name: "1person2"}, {id: 3, name: "4person3"}]; 

  $scope.selected = { person: $scope.persons[1] };
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
  <table>
    <tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
      <td> {{ person.name}}</td>
      <td> <input type="radio" name="radio" ng-model="selected.person" ng-value="person"/></td>
    </tr>
  </table>
  
  <hr>
  <p>Selected Person:</p>
  <pre ng-bind="selected.person | json"></pre>
</div>

Answer №2

Using $index in this context won't work because it represents the index of the loop, not the index of the item in the array. One way to fix this issue is to either have an index property in the data source or create a function to return the relevant index.

var app = angular.module('app', []);

app.controller('ctrl', ['$scope', function(scope) {

  scope.persons = [{
    name: 'ABC index 0'
  }, {
    name: 'EFG index 1'
  }, {
    name: 'XYX index 2'
  }];

  scope.selectedPerson = "1";
  scope.getIndex = function(item) {
    return scope.persons.indexOf(item);
  }
}])

angular.bootstrap(document.body, ['app']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="ctrl">
  Selected Person:-
  <pre>{{persons[selectedPerson] | json}}</pre>
  <hr/>
  <table>
    <tr class="restTable" data-ng-repeat="person in persons|orderBy:'name'">
      <td> {{ person.name}}</td>
      <td>
        <input type="radio" name="radio" ng-model="$parent.selectedPerson" value="{{$parent.getIndex(person)}}" />
      </td>
    </tr>
  </table>
</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

Modifying the CSS style of an element on PageA by clicking a button on PageB

For my app, I am incorporating tabs. I want to implement a user button that, when clicked on tab-detail.html, will update the CSS of an element located on its parent tab page, tab.html. .controller('TabCtrl', function($scope,Tabs) { $scope.t ...

When Utilizing an async Task Method, DbContext is Properly Disposed

Currently, I have set up an async Task method to handle the IAuthenticationFilter interface. After logging in successfully, I can access an API with no issues when it has this attribute. However, if I revisit the API later on, an exception is thrown. publ ...

When trying to access localhost:5000, the index.js file is unable to retrieve /

const NutritionAPI = require('./nutritionapi'); const nutService = new NutritionAPI('50cee42503b74b4693e3dc6fccff8725','2755697297a84ac5a702461b166e71f6'); // Setting up Express webhook const express = require('express&ap ...

Utilizing a range input (slider) to extract data of importance

When dynamically adding a slider to a page using a specific string, like the one shown below: "<input type=\"range\" name=\"aName\" min=\"1\" max=\"9\"/>"; After appending it to the page with pure JavaScript, ...

To ensure a successful redirection process without information loss, it is essential to address any potential issues with data input into

How can I properly implement a page redirection? Below are the relevant code snippets. <link rel="stylesheet" type="text/css" href="payout.css"/> <font face='calibri'> <?php session_start(); $conn = @mysql_connect("localho ...

What is the best way to access and interpret headers received from my API using angular?

I have a piece of code similar to this on my website domain.com: $http.post("http://api.domain.com/Controller/Method", JSON.stringify(data), { headers: { 'Content-Type': 'application/json' } }) ...

Error: The JSON data contains an unexpected token at the beginning Express

I am currently following a tutorial (here) to establish a connection between Express and React Native. I have a server.js script running which connects to the client (App.tsx) on my IP address using port 3000. The server and app are running simultaneously ...

I am currently facing an issue with validating forms in JavaScript Document Object Model (DOM)

Whenever I click on a field and move to another one, the span tag turns red. Then, after pressing the submit button, an alert message pops up. However, if I turn the span red, fill in the field, and press the submit button, it shows success even if other f ...

Show spinner until the web page finishes loading completely

Could anyone guide me on how to display Ring.html for a brief moment until About.html finishes loading completely? I need the Ring.html page to vanish once About.html is fully loaded. As a beginner in web development, I would greatly appreciate your assist ...

Codemirror - Advanced Auto-Suggest Feature with Separator

Can a separator be easily added in the hints/autocomplete addon? This separator would help transform the suggestion box to look like: f1 f2 f3 --- var1 var2 ...

Organizing a JSON array and displaying it using the $.each function

My JSON array is structured like this: "series": [{ "book": 1, "chapter": 1, "title": "Title of this chapter", }, { "book": 1, "chapter": 2, "title": "Title of this chapter", }, { "bo ...

The strict-origin-when-cross-origin policy is enforced when submitting a POST request through a form to a specific route

Currently, I am diving into the world of Node.js, express, and MongoDB by reading Greg Lims's book. However, I've hit a roadblock when trying to utilize a form to submit data to a route that should then output the body.title of the form in the co ...

What sets defineProps<{({})}>() apart from defineProps({ }) syntax?

While examining some code written by another developer, I came across the syntax defineProps<({})>(). After doing some research, I couldn't find any resources that helped me understand this particular syntax. My Way of Defining Props defineProp ...

iOS fixed positioning and scrolling

One of the current challenges we are facing involves implementing an action button similar to the one found in GMail for adding new content. This button needs to remain fixed during scroll. Here is the HTML code: <div class="addButton actionButton" on ...

ajaxStart - Display change inconsistency

These are some helpful comments to shorten and improve the readability of the code In my current project, I am using Javascript (Ajax) along with PHP (Laravel). I encountered an issue where I have set up two listeners in my ajax function. One listener is ...

Modify a property within an object stored in an array using React with Redux

When trying to dispatch an action that updates values in the redux state by passing an array, I encountered an issue. It seems that despite attempting to update the array by changing object values, I kept facing this error - "Cannot assign to read only pro ...

Abstraction of middleware functions

After reviewing my middleware Express functions, I realized that there is repeated code. The first function is as follows: const isAdmin = async (req, res, next) => { try { const requestingUser = await knex('users') ...

MongoDB Driver Alert: MongoError - Cursor Not Found. Cursor ID 7820213409290816 was not located in the specified namespace db_name.collection_name

Having successfully created a Nodejs API server that connects to AWS MongoDB (version: 3.6), everything seems to function flawlessly when calling one specific API endpoint (api/lowest). However, upon making multiple simultaneous calls to this API (15 in to ...

Steps to retrieve a rejected object with an error stored in it in the following .then() function

Within my chain of promises, there is a specific promise that needs to log an error but pass the remaining data to the next .then() const parseQuery = (movies) => { return new Promise((resolve, reject) => { const queries = Object.keys( ...

Generating ChartJS in Real-time

I have a straightforward form where the user selects a start date and an end date. Once these dates are selected, the tool automatically fetches data from a website in JSON format. Below is the code for my Angular controller: (function () { angular.m ...