What is the best way to send the link's ID to an AngularJS controller?

I have a scenario similar to the following:

<a href="#" title="Post 1" id="car1"> Audi car 
</a>

<a href="#" title="Post 1" id="car2"> BMW car 
</a>

How can I pass the ID to the controller? I attempted the following:

<a href="#" title="Post 1" id="car1" onclick="getCarID(this.id)" > Audi car </a>

This method works outside of the Angular controller, but I would like it to be inside the controller. It seems that using ng-click is necessary, however, this.id will not function. How can this be resolved? In my controller and getCarID function, I have implemented it as follows:

angular.module('myModule')
.controller('carController', function($scope) {

    $scope.getCarID = function(elementID) {  
        var car = document.getElementById(elementID);
        console.log(elementID + " has been clicked");
    }
)}

If anything is unclear or requires further explanation, please leave a comment and I will update the question accordingly.

Thank you for your assistance.

Answer №1

Why not utilize the id of the target event?

<a href="#" title="Post 1" id="car1" ng-click="getCarID($event)">

Here is how you can handle it in your controller:

$scope.getCarID = function(event) {
   var id = event.target.id;
}

function Ctrl($scope) {

    $scope.action = function(event) {
        console.log('clicked id is: ' + event.target.id);
    };
}
<!doctype html>
<html ng-app>
   <head>
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
   </head>
   <body>
      <div ng-controller="Ctrl">
         <a id="123" ng-click="action($event)">click</a>
      </div>
   </body>
</html>

Answer №2

Make sure to include the missing quotation mark in this code snippet:

<a href="#" title="Post 1" id="car1" onclick="getCarID(this.id)" > Audi car  </a>

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

Error! The function worker.recognize(...).progress is throwing an error. Any ideas on how to resolve this

Here is the code snippet: //Imports const express = require('express'); const app = express(); const fs = require("fs"); const multer = require('multer'); const { createWorker } = require("tesseract.js"); co ...

Disabling prefetch in next.config.js: A comprehensive guide on eliminating data prefetching in Next.js

Typically, in many cases, the disabling of prefetching is achieved by specifically setting a link to not preload. An example of this can be seen below: <Link href="/about" prefetch={false}> <a>About us</a> </Link> My go ...

Tips for implementing server-side rendering in Jade using an Array of JSON objects instead of just a single JSON object

In my Node.js server, I am working with an array of JavaScript objects retrieved from a MySQL query. To pass this array to my Jade template, I use the following code in my router.js: data = JSON.stringify(rows[0]); res.render('yourUploads', {fro ...

The Express application encounters a 500 Internal Server Error due to a TypeError where the Object #<EventEmitter> does not contain the method 'hr

The staging instance of my webapp is encountering an issue: Express 500 TypeError: Object #<EventEmitter> has no method 'hrtime' at Object.logger [as handle] (F:\approot\node_modules\express\node_modules\connect ...

Invoke the javascript function by referencing the JavaScript file

I'm encountering an issue with two JavaScript files. One file uses the prototype syntax, while the other utilizes jQuery. Unfortunately, they don't seem to work harmoniously together. I've attempted calling the functions within the files usi ...

can you explain which documents outline the parameters that are passed into the express app.METHOD callback function?

As a beginner in javascript and nodejs, I often struggle with understanding callback functions. One thing that particularly confuses me is determining what arguments are passed into a callback function. Let's consider the following example: app.get( ...

Obtain the value of an element from the Ajax response

Just starting out with Jquery and Ajax calls - here's what I've got: $(document).ready(function () { $.ajax({ type: "GET", url: "some url", success: function(response){ console.log(response); } }) }); Here's the ...

Issue with pagination not updating when a checkbox is clicked

My goal is to create a filter function, but I am encountering issues with pagination when filtering. Specifically, when I click on the "Mobile Phone" checkbox, it only displays one record on the first page, two records on the second page, and so forth. Add ...

AngularYelp: Node Integration for Enhanced Functionality

Embarking on a new learning journey here, so please bear with me... Discovered node-yelp while browsing Yelp's API docs. Check it out here. // Request API access: http://www.yelp.com/developers/getting_started/api_access var Yelp = require('yel ...

How can parameters be included in ng-href when using ng-click?

So I have this list of products and I want to pass the current product id when clicking on ng-href by using a function with ng-click in the ng-href. This is what my html file looks like: <div class="agile_top_brands_grids" ng-model="products" ng-repe ...

Using Angular JS: Implementing ng-repeat with a personalized directive and a fluid model

I have a template structured like this: <div class="row search-panel"> <div ng-show="loadingAirports"> <i class="glyphicon glyphicon-refresh"></i> Searching... </div> <div ng-show="noResults"> ...

Ways to update a nested object by utilizing the setState method

I have a situation where I need to modify the key/value pairs of an object in my state. Specifically, I need to add a key/value pair to the object with an ID of 13. Please refer to the attached photo for reference. Although I know how to use setState, I ...

Having trouble displaying Json data on an HTML page?

I am trying to incorporate a local JSON file into an HTML page using JavaScript. I have successfully loaded the data from the JSON file into the console, but I'm encountering issues when trying to display it on the HTML page. Could someone please revi ...

AngularJS can retrieve the selected value from a select tag

<select ng-model="data.person"> <option value="1" selected="">1 pax</option> <option value="2">2 pax</option> </select> The ng-model above returned "1 pax," but how can I retrieve ...

Is there a way to transform a JSON object into a custom JavaScript file format that I can define myself?

I have a JSON object structured as follows: { APP_NAME: "Test App", APP_TITLE: "Hello World" } My goal is to transform this JSON object into a JavaScript file for download. The desired format of the file should resemble the follo ...

What is the process for generating a null result cursor upon publication?

Is it possible to return an empty cursor in Meteor? Meteor.publish('example', function(id) { check(id, Match.Maybe(String)) if (!this.userId) return [] }) Although I want the publication to return an empty result when the user is not lo ...

Exploring the process of linking multiple checkbox fields in a form with an ajax request

I have attempted the following method, but it is not working. I am able to retrieve the name from the form, but nothing gets assigned to the "sharewith" variable. My goal is to assign all selected checkboxes to one id called "sharewith" and then send them ...

Struggling to configure Angular html5mode and UrlRewriteFilter to function correctly with specific URLs

In my web application, I am utilizing AngularJS 1.3 along with a Java/Jersey REST API. After successfully implementing html5mode using the Tuckey UrlRewriteFilter, I have managed to change simple URLs like localhost:8080/#/page to just localhost:8080/page. ...

What would be the best way to display a label once the zoom level exceeds a certain threshold in Leaflet?

As someone new to the Leaflet library and JavaScript in general, I'm currently facing a challenge with showing/hiding a leaflet label based on the zoom level. The markers are within a 'cluster' layer loaded via AJAX callback, and I bind the ...

Creating JSON structure following $http.get using AngularJS

Update If you're struggling to fit JSON data from Splunk into Highchart, this demo with Highchart-ng and a JSON rebuild solution could be just what you need. Check it out here: http://plnkr.co/edit/Nl47Hz5Cnj1jvUT3DTBt?p=preview -- I'm facing ...