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

How can I import a JavaScript file from the assets folder in Nuxt.js?

I have explored multiple methods for importing the JS file, but I am still unable to locate it. Can anyone guide me on how to import a JS file from the assets folder to nuxt.config.js and have it accessible throughout the entire website? nuxt.config.js he ...

Trying to use the `await` keyword results in a "SyntaxError: Unexpted identifier" message, even when used within an `async` function

Encountering an error with Javascript's await when using it inside an async module let ImagesArray = await getImages(); ^^^^^^^^^ SyntaxError: Unexpected identifier at createScript (vm.js:80:10) at Object.runInThis ...

Error: foobar is not defined within this scope (anonymous function)

I'm facing an issue with a JavaScript file hosted on a domain called foobar.com. at http://foobar.com/static/js/main.js: $(document).ready(function() { function foobar(bar){ $.ajax({ url: "/site/foo/", ...

Struggling to make even the most basic example work with TypeScript and npm modules

After stumbling upon this repository that made using npm modules within a Typescript program look easy, I decided to give it a try by forking it and making some changes. My goal was to add another package to get a better understanding of the process. So, I ...

Utilizing an object as a prop within React-router's Link functionality

Looking for a solution to pass the entire product object from ProductList component to Product component. Currently, I am passing the id as a route param and fetching the product object again in the Product component. However, I want to directly send the ...

JavaScript issue: Shallow copy does not reflect updates in nested JSON object

Within my coding project, I came across a nested JSON object that looks like this: var jsonObj = { "level1" : { "status" : true, "level2" : {} // with the potential to extend further to level 3, 4, and beyond } } My objective is si ...

Determine if the object's value is present

My current JavaScript setup looks like this: var NAMES = []; function INFO(id,first,middle,last){ var newMap = {}; newMap[id] = [first, middle, last]; return newMap ; } Next, I have the following code block: for (var j = 0; j < NUMBER.leng ...

The height of the ReactPlayer dynamically adjusts to accommodate content beyond the boundaries of the page

I have a video on my webpage that I want to take up the entire screen, but currently, users have to scroll a bit to reach the bottom, which is not ideal. This is my JavaScript: <div id="page"> <div id="video-container"> ...

The form within the dynamically loaded AJAX content is malfunctioning

My webpage is set up to load content from a separate file (content.php) into a div and refresh it every 5 seconds. In the content.php file, I have a form (basic HTML without javascript) that works fine when accessed directly at (example.com/content.php). ...

Tips on preventing duplicate websocket clients in VueJS

Each time I access a component, it triggers the socket.on event. Additionally, there is a Vuejs button component as shown below. So when I emit to the 'socket.on('voice')' event in nodejs, the nodejs socket emits to the 'socket.on( ...

"Sharing JSON data with the client side using Express and Node.js: A step-by-step guide

I am currently working on an application that requires sending form data through XMLHttpRequest. The process involves validating the form data on the server side and then providing feedback to the client based on the validation result. In this project, I a ...

How can we dynamically update an environment variable for the IP address before running npm start in a React application?

Currently, I am attempting to automatically set the REACT_APP_DEPLOY_DOMAIN variable in the .env file. Here is one approach that I have implemented to address this challenge. In the script below, I am extracting my IP address: const os = require("os"); ...

Ways to disperse items within another item

I have an inner object nested inside another object, and I am looking to extract the values from the inner object for easier access using its id. My Object Resolver [ { _id: { _id: '123456789', totaloutcome: 'DONE' }, count: 4 }, { ...

Components loading in Angular result in lat long being undefined in google map integration

I am currently utilizing Ionic-angular AGM. I am facing an issue where I am unable to retrieve my current location when the component loads, as it seems like the component is being fired before the latitude and longitude are ready. How can I make this proc ...

Malfunction in parsing the post request body

Recently, I have been facing an issue while attempting to execute a $http.post request in this manner: $http({ method: 'POST', url: '//192.168.2.1:3000/auth/signup', data: $scope.credentials, headers: { 'Content- ...

A Python program that creates an HTML webpage

I am currently working on a Python script that, when launched on localhost with Apache, will generate an HTML page. Here is the script (test.py): #!/usr/bin/python # -*- coding: utf-8 -*- import cgitb cgitb.enable() import cgi form = cgi.FieldStorage() ...

How to retrieve an object's property within a component

Currently, my goal is to retrieve the email property from the user object {"name":"test", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="582c3d2b2c182c3d2b2c7620">[email protected]</a>"} I want to achie ...

What could be the reason for the absence of the back button?

Having trouble understanding why the back button isn't showing up when I navigate to an <ion-view> app root state template: <ion-side-menus> <ion-side-menu side="left"> <div class="list"> <!-- ... --> & ...

Ensuring child input components are validated upon submission using Vee-Validate and Vue.js 2

Currently, I am working on creating a Registration form with multiple "Input Field" components that require validation once the Submit button is pressed. While each input field validates individually when the text is changed, I am struggling to implement a ...

Using TypeScript for Immutable.js Record.set Type Validation

Currently, I'm utilizing Immutable.js alongside TypeScript for the development of a Redux application. In essence, the structure of my State object is as follows: const defaultState = { booleanValue: true, numberValue: 0, } const StateRecord = ...