Modify ng-repeat to align with the object's format

I've got this interesting object structure:

 $scope.hobbies = {
    list: [
      {
        "PersonId": 23,
        "PersonName": "John Smith",
        "Hobbies": [
          {
            "HobbyTitle": "Paragliding",
            "HobbyId": 23
          },
          {
            "HobbyTitle": "Sharking",
            "HobbyId": 99
          }
        ]
      }             
    ]
   };

Currently, I'm working on creating a view that allows users to select hobbies for each person.

If you want to take a peek at my progress so far, here's a link to the plunker here.

The issue I'm facing is that all selected hobbies are showing up under every person. This happens because I'm simply adding all selected hobbies to a single selectedHobbies array.

  $scope.addHobbyItem = function (item) {
    var index = $scope.selectedHobbies.list.indexOf(item);
    if (index === -1) {
      $scope.selectedHobbies.list.push(item);
    }
  };

This approach doesn't quite cut it, as each selected hobby ends up being displayed under every person. How can I modify the code to align with the ng-repeat loop over the selectedHobbies?

For reference, below is the HTML snippet I'm working with. Also, there's a directive in place to detect clicks on the hobby container and call the addHobbyItem() function:

<div data-ng-repeat="personHobby in hobbies.list">
  <div>
    <div style="border: 1px solid black; margin: 10px 0 10px">
      <strong>{{ personHobby.PersonName }}</strong>
    </div>
  </div>
  <div class="">
    <div class="row">
      <div class="col-xs-6">
        <div data-ng-repeat="hobby in personHobby.Hobbies" data-ng-if="!hobby.selected">
          <div data-hobby-item="" data-selected-list="false" data-ng-class="{ selected : hobby.selected }"></div>
        </div>
      </div>
      <div class="col-xs-6">
        <div data-ng-repeat="hobby in selectedHobbies.list">
          <div data-hobby-item="" data-selected-list="true"></div>
        </div>
      </div>
    </div>
  </div>
</div>

Answer №1

Ensure that your chosen interests are stored as a map, with the person's id as the key and a list of their selected hobbies as the value. Take a look at this plunker for reference

  $scope.selectedHobbies = {
    map: {}
  };

  // Function to add a new hobby item to our selection
  $scope.addHobbyItem = function(pid, item) {
    if(!$scope.selectedHobbies.map[pid]) {
      $scope.selectedHobbies.map[pid] = [];
    }
    var index = $scope.selectedHobbies.map[pid].indexOf(item);
    if (index === -1) {
      $scope.selectedHobbies.map[pid].push(item);
    }
  };

When using the directive, make sure to call addHobbyItem with the respective person's id

scope.addHobbyItem(scope.personHobby.PersonId, scope.hobby);

To display each person's selected hobbies in your HTML, iterate through them like so:

    <div data-ng-repeat="hobby in selectedHobbies.map[personHobby.PersonId]">
      <div data-hobby-item="" class="add-remove-container--offence" data-selected-list="true"></div>
    </div>

Answer №2

Here is an example:

http://example.com/edit/sample

Utilizing the $parent.$index method, I was able to generate an array of arrays that holds different hobbies for each individual.

 $scope.addHobbyItem = function (item, index) {

     var ine = $scope.selectedHobbies[index].indexOf(item);
     if (ine === -1) {
        $scope.selectedHobbies[index].push(item);
     }
 };

 function hobbyClickEvent() {
    if (!$(element).hasClass('selected')) {

      scope.addHobbyItem(scope.hobby, scope.$parent.$index);
    } else {
      scope.removeHobbyItem(scope.hobby);
    }
  }

In the HTML section:

<div data-ng-repeat="hobby in selectedHobbies[$index]">
    <div data-hobby-item="" class="add-remove-container--offence" data-selected-list="true"></div>
</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

Type parameter in express.js route

If I have this specific route in my Express.js server: router.get('/ad/:id', (req, res) => { const { id } = req.params Ad.getAd(id, (err, resp) => { if(err){ return handleError('Failed to load an ad' ...

Exploring nested arrays within JSON objects - techniques for accessing specific properties

Having some difficulty with the JSON data I received. The structure is as follows: [ [ { "items": [ { "id": "xxxxxxx", "name": "xxxxxxxxxx", "description": "xxxxxxxxxxx" } ...

Utilizing the "ng-view" directive of AngularJS within an ASP.NET MVC web application to handle routing

I am currently developing a web application using ASP.NET with MVC and AngularJS. I am facing an issue getting AngularJS to work with an "ng-view" in a cshtml site since I have no prior experience working with AngularJS and MVC. My problem is: AngularJS ...

Tips for enhancing the efficiency of your Node.js and Express.js code while steering clear of callback hell

One of the controllers in my application contains a method that is responsible for printing an array of URLs using the webshot package. Below is the code snippet in question: router.post('/capture', function (req, res, next) { //Check params ...

Set up input fields for text within an Angular directive

Trying to initialize input fields in a directive with server data, but facing issues with ng-model. Previously used $scope.field1 = $scope.first.field1 in the controller before using directive. Code simplified for readability: In controller: app.control ...

Implement table styling after concealing rows (Twitter Bootstrap)

Hey there, I am currently working with Bootstrap and have a table that is striped. Users can filter this table by selecting different options on a form. The Javascript code I've written interprets the form input and hides rows in the table that don&ap ...

Audio not functioning on Android version 2.3.6 due to HTML5 issues

I've created an Android Audio Application that functions flawlessly with html5 Audio. However, I've encountered a problem where the audio won't play on certain phones. I'm utilizing a basic HTML5 feature. I've tried various solut ...

Close the menu in Angular 7 by clicking outside of it

I am seeking a way to detect when a click event occurs inside the parent div #menu, regardless of any HTML tags present within it. Using nativeElement.parent did not provide the desired result. Here is the HTML code: <button #toggleButton (click)="to ...

Loading indicator for buttons

Issue with submit button onclick function (onClick="mandatoryNotes()"). It is taking a while to load, so a preloader script was added. The preloader is now working, but the function is not being called. Seeking assistance. Thank you. function mandatoryN ...

Coordinates in a 3D space following a rotation

I have two specific points, C and P. My goal is to rotate point P around center C in three dimensions. How can I determine the new coordinates of point P after rotation? I am provided with two angles: 'yaw' and 'pitch'. The 'ya ...

Creating a user-friendly mobile navigation bar

Can someone help me with the code to create a button that displays the navigation bar when needed and hides it when not in use, similar to the one on apple.com? I'm working on this for a mobile device and would appreciate any suggestions or correction ...

How can I automatically submit a form upon page load with AJAX and receive the result in HTML format?

Attempting to automatically submit a form when the page loads using ajax and then retrieve the HTML (consisting of multiple divs that will be echoed on the AJAX URL) back to my AJAX page. Firstly, the code successfully auto submits the form but fails to t ...

Link customer's name to importance

This application involves creating, reading, updating, and deleting client information. The list view should be sorted on the server, so it is essential to prioritize Firebase references on the client side. angular.module('MyApp') .controller ...

React: Is it possible to separate common functionality into its own function?

There is a need to refactor common functionality into a separate function called getQuote(), but encountering errors when attempting this in React. Any assistance would be highly appreciated. index.js: import React from 'react'; import ReactDOM ...

Executing a function on the node server using pure JavaScript: Step-by-step guide

My latest project involves creating a typing game that utilizes a JSON file as the database. To achieve this, I am leveraging Nodejs along with the fs module to handle the .json file manipulation. The goal is to have a main.js file responsible for managing ...

A Guide to Scraping a Dropdown List with JavaScript Using Scrapy in Python

I am looking to extract the list of available sizes from the 'size' section at this specific web address: My goal is to collect a list of the current in-stock sizes. How can I go about achieving this? Below is the complete code snippet I am wor ...

What is the purpose of having several script tags following the creation of NextJS?

After running next build and next start, my application is still generating many JS files instead of a single entry point. I'm unsure if I missed a step as the documentation suggests this should be all that's required. https://i.stack.imgur.com/7 ...

The Postman application is unresponsive and the hashed password has not been created

I am currently attempting to create a hashed password using bcryptjs and then display that password using console.log for easy access and use. For testing my POST request, I am using Postman where my approach involves sending the request body with email a ...

Guide on sending table data in JSON format using jQuery

Here is a table I have: <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("button").click(function(){ // Looking for sugge ...

PHP failing to retrieve information

Having trouble with this specific file as it seems to be missing data in the address fields. Additionally, whenever "notes" are inputted, the Address data disappears. Any thoughts on how to resolve this issue? <tbody> ' ; $message .=&a ...