Displaying the specified item within an array using AngularJS

My application features a group of 'players' each with their own unique attributes that I want to showcase within a modal window and cycle through. The user interface is structured like this:

 <!-- Score Round Modal -->
  <div class="modal fade" id="myScoreModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" ng-repeat="player in players">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Score for {{player.data}}</h4>
        </div>
        <div class="modal-body">
...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal" ng-click="cancelRound()">Cancel</button>
          <button type="button" class="btn btn-warning" ng-click="previousPlayer()">Previous</button>
          <button type="button" class="btn btn-default" ng-click="nextPlayer()">Next Player</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="calculateRound()">Finish</button>
        </div>
      </div>
    </div>
  </div>

I have successfully displayed the player's first name, but now I aim to cycle through using the functions previousPlayer() and nextPlayer(). In the JavaScript section, there is a variable named currentPlayer which I increment and decrement as follows:

$scope.nextPlayer = function () {
    // Cycles to next player cards within the round
    $scope.currentPlayer++;
    console.log($scope.currentPlayer);
};


$scope.previousPlayer = function () {
    // Cycle to previous player cards within the round
    $scope.currentPlayer--;
    console.log($scope.currentPlayer);
};

The objective here is not only to view but also to modify the player model.

Answer №1

If you want to showcase player data for one player at a time, having just one modal window should suffice.

To simplify your HTML, you can avoid using ng-repeat and ng-if - simply access the current player using players[currentPlayer]:

<div class="modal fade" id="myScoreModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
          <h4 class="modal-title" id="myModalLabel">Score for {{players[currentPlayer ].data}}</h4>
        </div>
        <div class="modal-body">
        ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-danger" data-dismiss="modal" ng-click="cancelRound()">Cancel</button>
          <button type="button" ng-if="currentPlayer > 0" class="btn btn-warning" ng-click="previousPlayer()">Previous</button>
          <button type="button" ng-if="currentPlayer < players.length - 1" class="btn btn-default" ng-click="nextPlayer()">Next Player</button>
          <button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="calculateRound()">Finish</button>
       </div>
     </div>
   </div>
 </div>

See it in action on JsFiddle: http://jsfiddle.net/kxUR9/16/

Answer №2

To display only one player, it is not necessary to use ng-repeat.

You can simply create a new property called $scope.player

$scope.currentPlayer = 0;

function setPlayer() {
  if ($scope.currentPlayer >= 0 && $scope.currentPlayer < $scope.players.length) {
    $scope.player = $scope.players[$scope.currentPlayer];
  }else{
    alert('At end of players');
  }
}

setPlayer();

$scope.nextPlayer = function() {
  // Moves to the next player's cards within the round
  $scope.currentPlayer++;
  setPlayer();
};
$scope.previousPlayer = function() {
  // Moves to the previous player's cards within the round
  $scope.currentPlayer--;
  setPlayer();
};

In the view, just remove the ng-repeat

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

Preventing the closure of a Nativescript Angular modal when tapping on the background

I'm relatively new to NativeScript and I'm trying to figure out how to prevent my custom modal from closing when the user taps on the background, specifically for Android devices. It's easy to achieve this with the dialogs provided by Nativ ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

How can we modify specific values of an object using Lodash and return the updated object?

const fruits = { apple: 2, orange: 3, grape: 4, banana: 5 } My aim is to adjust the values of certain fruits while being able to reference their current values. For example: const premiumFrutis = _.doSomething(fruits, apple + 2, banana + ...

Start flicker issue in Vue 3 transition

I have created a carousel of divs that slide in and out of view on the screen. However, I am facing an issue where during the start of each transition, when a new div is rendered (i.e., the value of carousel_2 changes), it appears without the transition-en ...

Extension for capturing videos on Chrome or Firefox

I am interested in developing a Chrome or Firefox extension that can capture video from a window or tab. My goal is to record full screen videos, such as those on YouTube, for offline viewing similar to a DVR for online content. Creating an extension see ...

Pass a link by pressing Enter

Although the title may seem odd, I'll explain what I'm attempting to accomplish. I have a login form with two input fields, a checkbox, and a submit button. You can view a screenshot of it here: https://i.sstatic.net/nE1FY.png The terms of use a ...

Attempting to incorporate Font-Awesome Icons into the navigation bar tabs

As a newcomer to React, I've been attempting to incorporate Font Awesome icons into my secondary navigation bar. Despite using switch-case statements to iterate through each element, all the icons ended up looking the same, indicating that only the de ...

incorrect implementation of react lifecycle phases

My Sharepoint Framework webpart includes a property side bar where I can choose a Sharepoint List, and it will display the list items from that list in an Office UI DetailsList Component. Although all REST calls are functioning properly during debugging, ...

`Error: Unresolved reference to Angular service`

I'm encountering an issue in my Ionic/Cordova application where I am trying to implement a loading message using $ionicLoading, but I keep getting the error: ReferenceError: $ionicLoading is not defined Does anyone know how I can successfully pass $ ...

Guide to testing Vuex Mutations with Vue-test-utils and Jest

I have reviewed a few tutorials on mocking and testing Vuex actions, but I have struggled to implement them successfully on my own. Despite following the steps outlined in the links provided, I consistently encountered an issue where toHaveBeenCalled would ...

Converting JSX files to TSX files: a step-by-step guide

I am facing an issue with this particular component on the website. It is currently in .jsx format while the rest of the website uses .tsx files. I need to convert this specific component into a .tsx file. Can someone provide assistance or guidance? Despit ...

Avoid reactivating focus when dismissing a pop-up menu triggered by hovering over it

I am currently utilizing @material-ui in conjunction with React. I have encountered the following issue: In my setup, there is an input component accompanied by a popup menu that triggers on mouseover. Whenever the menu pops up, the focus shifts away from ...

Could somebody clarify the situation with the `push` function?

Something seems off with the behavior of the push method. Instead of pushing to only one index within the forEach, it appears to be pushing to all three indexes. Can anyone see what might be causing this unexpected result? let arrayToReduce = [ [ 1, 2, ...

Exploring Angularjs End-to-End Testing using Angular-UI's Select2 Component

I am facing a challenge with a partial that has a select2 element using Angular UI http://angular-ui.github.io/ The problem is that the element is marked as required, and even though I have managed to set the field through the code provided below, the req ...

Create various designs for a section of a webpage

My goal is to create a coding playground using flex-box to position different panels. Here is an example in JSBin, with the following html code: <div class="flex-box"> <div class="col" id="html-panel"> <p>html</p> </div& ...

What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked. https://i.sstatic.net/rEMbG.jpg When hovering over an area without an element, the assigned tooltip is d ...

The concatenation of Ajax results appears to append to the existing data

My ajax function handles uploading comments to a form, which then returns the same string. If successful, the comment is added to a comment box and the input text is cleared. The issue arises when a user adds another comment; the new comment is appended w ...

Utilize the keyboard's vertical arrows to adjust values as needed

Implement the functionality to increase and decrease the value in a label or p tags using the onkeydown and onkeyup events, without requiring a textbox input. I have come across numerous examples, but they all rely on textboxes. I am looking for a soluti ...

Trying to toggle between two Angular components within the app component using a pair of buttons

Currently, I am developing an application that requires two buttons to display different nested apps. Unfortunately, I am unable to use angular routing for this particular design. These two buttons will be placed within the app.component. When Button A i ...

Managing JSON data retrieval and manipulation with REST API in Node.js and MongoDB

My technology stack includes Node.js and MongoDB with a rest api. The input data I'm dealing with looks like this: var doc={"name":"ABX", duedate : new Date() } Before sending it to the server, I stringify the data: /rest/update?doc=JSON.s ...