Creating an array to store ng-click events in AngularJS is a common task for developers. Here's

I have a project where I'm tasked with collecting multiple user-selected items and sending them to the server. On my view, there's a list that users can click to select items. Here's a snippet of my HTML:

HTML

<div ng-repeat="topicList in searchCtrl.topic">
    <div ng-repeat="topicTerm in topicList">
       <p>{{topicTerm.number}}&nbsp&nbsp{{topicTerm.name}}</p>
       <div ng-repeat="subTopic in topicTerm.subTopics">
          <a href="" ng-click="searchCtrl.select($event)">{{subTopic.number}}&nbsp&nbsp{{subTopic.name}}</a>
       </div>
    </div>
</div>

The anchor tag allows users to click on items, while also giving each item a unique ID for collection in an array or variable. This collection will be sent to the server via form submission.

This is what my controller looks like:

JavaScript Controller

angular.module('myApp').controller("searchController", function($log, searchService, $scope){
    var self = this;

    self.initializeSearch = function(){

        self.searchEntry = 
            { 
            "contact":{     
                "person": "",      
                "organization": ""
            },  
            "request": {      
                "input": "",      
                "language": "en"
            },  
            "topicIds": []
            };

    // The POST request must looks like above

The goal is to collect the clicked subTopics IDs in an Array "topicIds : []" so that the POST request mentioned above can be successfully sent. The searchService is an Angular service used to fetch topics from the server and handle POST requests.

This is how my JSON data is structured:

JSON API

{  
   "TopicList" :[  
   {
      "id": "798790fa-78c8-4f00-8179-9e70f40adb14",  
      "name": "Topic1",  
      "number": 1.0,  
      "subTopics": [              
         
       ]      
   },
   ...
  ]
}   

How can I create a function or array that collects the IDs through an ng-click event?

Thank you in advance.

Answer №1

Avoid using the $event in your code, simply pass the subTopic.id or similar parameter in your ng-click event like this:

ng-click="searchCtrl.select(subTopic)"

In your controller, you can implement the following logic:

angular.module('myApp').controller("searchController", function($log, searchService, $scope){
    var self = this;
    var subTopicIds = []; // an array to store subTopicIds

    self.select = function(subTopic) {
        subTopicIds.push(subTopic.id);
    }

    self.initializeSearch = function(){

        self.searchEntry = 
            { 
            "contact":{     
                "person": "",      
                "organization": ""
            },  
            "request": {      
                "input": "",      
                "language": "en"
            },  
            "topicIds": subTopicIds // use the previously created object
            };
    ...

Answer №2

To obtain an ID within angular, you can use the following method:

<div ng-click="recordClick($event)">Click</div>

This code snippet will pass the click event to the recordClick function. From there, you can access its target property (which refers to the specific div that triggered the click) and add it to an array.

$scope.clickArray = [];
$scope.recordClick = function(event){
    clickArray.push(event.target);
}

Answer №3

I managed to resolve this issue by including the subTopics ID in the ng-click function as a parameter. Additionally, I needed to trigger another event upon user click, which I passed as a second argument. As a result, both events now function as intended with a single ng-click.

Below is the updated code snippet:

HTML

<div ng-repeat="topicList in searchCtrl.topic">
  <div ng-repeat="topicTerm in topicList">
    <p>{{topicTerm.number}}&nbsp&nbsp{{topicTerm.name}}</p>
    <div ng-repeat="subTopic in topicTerm.subTopics">
      <a href="" ng-click="searchCtrl.select(subTopic.id, $event)">{{subTopic.number}}&nbsp&nbsp{{subTopic.name}}</a>
    </div>
  </div>
</div>   

And here is the corresponding controller code:

Controller

angular.module('myApp').controller("searchController", function($log, searchService, $scope){
var self = this;
var subTopicIDs = [];

    self.select = function(TopicIDs, event){
        subTopicIDs.push(TopicIDs);
        $(event.target).addClass('selor');  
        console.log(TopicIDs);
    }    

self.initializeSearch = function(){

    self.searchEntry = 
        { 
        "contact":{     
            "person": "",      
            "organization": ""
        },  
        "request": {      
            "input": "",      
            "language": "en"
        },  
        "topicIds": subTopicIDs
        };

This approach successfully addressed my concern. Many thanks to Tom and OceansOnPluto for their insights.

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 could be causing my For Each loop to overlook certain items within my array?

Here is the complete code I am working with: FirstRow = Columns("B").Find("B").MergeArea.Row LastRow = Columns("B").Find("B").MergeArea.Row + Columns("B").Find("B").MergeArea.Rows.Count - 1 First ...

Leveraging Arrays with AJAX Promises

I am currently working on making multiple AJAX calls using promises. I want to combine the two responses, analyze them collectively, and then generate a final response. Here is my current approach: var responseData = []; for (var i=0; i<letsSayTwo; i++ ...

Preventing navigation without using the <Prompt> component in React Router DOM V6

I have recently discovered that in react-router-dom v5, it was possible to utilize the <Prompt> component to prompt the user before a page transition occurs, allowing them to prevent it. However, this feature has been removed in v6 with plans for a m ...

Enhance your list functionality in AngularJS by using the track by expression feature, which allows for easy

Is there a more efficient way to leverage the track by feature for ng-repeat with editable lists, where users can add and remove items? Each existing object is already assigned a unique ID, while a missing ID signals that the item needs to be created upon ...

The AJAX call to retrieve data from a file dynamically is experiencing issues

I am currently trying to use AJAX to dynamically retrieve data from my PHP page and display it on my HTML page. However, I am running into some issues with getting it to work properly. You can view the page here Here is the snippet from the HTML Page wher ...

Show me a list of all the commands my bot has in discord.js

Recently, I developed a Discord bot using discord.js and attempted to create a help command that would display all available commands to the user. For example, one of the commands is avatar.js module.exports.run = async(bot, message, args) => { le ...

What is causing the issue of the div not being removed from the label renderer in three.js

Hello, I've been trying to solve this issue for the third time now without much success. The problem I'm facing is related to creating a div at runtime and then attempting to remove it after clicking on it. Although I've tried removing the d ...

What is the proper way to utilize "three.module.js"?

I am currently learning how to utilize modules and decided to start with a simple example. However, I encountered an issue where the script does not want to run. I must be missing something crucial, but I can't seem to figure out what it is. I have tr ...

AngularJS - developing a unique directive with customized attributes embedded in the templateUrl

In my arsenal of text formatting templates, I have files named frecuencia-dia.html and frecuencia-mes.html, among others. My goal is to dynamically call a template using the attributes tipo (representing text type) and clave (variable scope). <ng-form ...

Angular JS not displaying texts properly

Within my code, I have implemented a feature to display an h4 element stating that there are no products found if the search query does not match any strings. However, I am encountering a strange bug where the text fails to appear as intended. Interestingl ...

Creating an asynchronous function in Node.js that returns a promise, but experiencing unexpected behavior when using console.log to display the result

Recently, I created a simple and compact API that determines the gender of a person. It functions by sending a get-request to a specific page which responds with a JSON object. This snippet illustrates how my module works: 'use strict'; const ht ...

Updating jQuery event behaviors based on the value of .html( 'string' )

Visit this link for more information. Feel free to modify the heading if you believe it needs improvement. General I manage a multilingual WordPress website with dynamic menu and navigation controlled through the WordPress admin panel. The multilingual ...

Display and conceal individual divs using jQuery

Despite my lack of experience with jQuery, I am struggling with even the simplest tasks. The goal is to display/hide specific messages when certain icons are clicked. Here is the HTML code: <div class="container"> <div class="r ...

Running different AngularJS applications on a single webpage

I am currently working with two separate apps on a single page. Navbar Module This module is situated in the navbar of the page and is included on every page of the application through the master layout file (using Laravel). It contains functions like se ...

How can I effectively develop a versatile user interface for a website using Ruby on Rails that is compatible with all

Currently, I am in the midst of developing a web application using Ruby on Rails. Occasionally, I encounter challenges with cross-browser compatibility when it comes to CSS and Javascript. Are there any strategies you recommend to reduce these issues dur ...

I've managed to mess up my code again; local storage was working fine, and now it's not. I'm completely clueless

I attempted to store the best game times in local storage by creating an empty array called gBestScores. I compared the value of the last best score to the current one and decided whether to push it into the array or not. However, despite my efforts, the ...

Create a folder in jsTree - the folder is generated before the user enters a name for it

I own a tree that I am able to create folders on. However, there is an issue with the process that is also present in the filebrowser demo found in the jsTree download. It's a user experience problem, so I will try my best to explain it clearly: 1) ...

An old-school Ajax request abruptly interrupted halfway through

function submitLogin(){ var username = document.getElementById('username').value; var password = document.getElementById('password').value; var testlabel = document.getElementById('testlabel').value; ...

When the response is manually terminated, the next middleware layer in express.js is invoked

I recently noticed an unusual occurrence: Even though I am explicitly ending the request using res.json() in one express middleware, the request still cascades down to the next middleware. It is important to mention that I am not utilizing next() anywhere ...

Data Mishmash Generated by the 'littlest' and 'largest' Functions

My current challenge involves utilizing two parallel arrays to determine which jar of salsa had the highest and lowest sales. The goal is to output the corresponding sales numbers, which will be converted into salsa names for display. However, I am encou ...