Giving ng-click the current HTMLElement

Can the HTMLElement be passed to an ng-click function set up on a controller?

Take a look at this example code:

<div ng-controller="Controller">
   <ul ng-repeat="item in items">
      <li ng-click="handleThisElement($element)" id="{{item.id}}" >{{item.name}}</li>
   </ul>
</div>

The Controller:

function ($scope) {
  $scope.items = [
    {name: 'Bilbo', id='Bilbo'},
    {name, 'Frodo', id='Frodo'},
    {name: 'Pippin', id='Pippin'},
    {name: 'Merry', id='Merry'},
    {name: 'Sam', id='Sam'}
  ];

  $scope.handleThisElement = function (element) {
     alert(element.id); // should alert (Bilbo || Frodo || Pippin || Merry || Sam)
  }

UPDATE:

Just to clarify, I am looking to retrieve the entire element, not just the id from the model.

Using $event.target may not work in certain versions of Internet Explorer.

Answer №1

The following HTML code snippet:

<div ng-controller="Controller">
   <ul ng-repeat="item in items">
      <li ng-click="handleThisElement($event)" id="{{item.id}}" >{{item.name}}</li>
   </ul>
</div>

Accompanied by the Javascript function:

function ($scope) {
  $scope.items = [
    {name: 'Bilbo', id='Bilbo'},
    {name, 'Frodo', id='Frodo'},
    {name: 'Pippin', id='Pippin'},
    {name: 'Merry', id='Merry'},
    {name: 'Sam', id='Sam'}
  ];

  $scope.handleThisElement = function ($event) {
     alert($event.target.id);
  }

Answer №3

Employ the `watch` method in AngularJS to achieve this

$scope.$watch(function () {
    return document.activeElement;
}, function update(newValue, oldValue) {
    $scope.oldActiveElement = oldValue;
});

Answer №4

give this a try

<div ng-app="myApp" ng-controller="MyController">
   <ul ng-repeat="hero in heroes">
     <li ng-click="selectHero(hero)" id="{{hero.id}}">{{hero.name}}</li>
   </ul>
</div>

function MyController($scope) {
   $scope.heroes = [
     {name : 'Spider-Man', id:'spiderman'},
     {name : 'Iron Man', id:'ironman'},
     {name : 'Captain America', id:'captainamerica'},
     {name : 'Black Widow', id:'blackwidow'},
     {name : 'Hulk', id:'hulk'}
   ];

   $scope.selectHero = function (selectedHero) {
    alert(selectedHero.id); // should alert (spiderman || ironman || captainamerica || blackwidow || hulk)
   }
}

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

Encountered a problem while establishing a connection to Firebase following the upgrade of

Ever since I upgraded angularfire to version 2.0.1 in order to support the latest Firebase version 3.2.0, my app has been unable to establish a connection with the database. I'm not sure what could be causing this issue. Here's the code that used ...

calling requestAnimationFrame from within a freshly created instance

I'm encountering an issue with executing an animation. Specifically, this problem arises within var ob1 = function() {};. Once triggered, the animation runs for a brief period before I receive the error message Uncaught RangeError: Maximum call stack ...

The HTML elements on the webpage are showing up incorrectly

When visiting thedaystaragency.com/home and scrolling down to our services section where the lightbulbs are located, it is apparent that they are misaligned and not functioning properly. I have provided the code that I am currently using, but I had to remo ...

What steps can I take to resolve the issue of item display in the dropdown menu?

My objective is to have a dropdown list with "title 1234" appearing first. When this option is selected, its value should be 1234. How can I achieve this? Here is the desired outcome: https://i.sstatic.net/CqWgn.png Currently, the list looks l ...

JavaScript that is subtle and lacks function parameters

Suppose you have: <div id="data" onclick="handleData(1)">Datum 1</div> and you prefer late binding instead: <div id="data">Datum 1</div> <script> $("#data").click(function() { handleData(1); }) </script&g ...

When the button is clicked, Shopify will automatically send an email notification to the Admin

Is there a Shopify API available to send an email to the admin when a button is clicked? Please note, this is not related to a contact form. I am looking for a way to trigger an email to the admin with dynamic information from the page by simply clicking ...

Locate specific words within the content and conceal them

Can anyone help me with a jQuery solution to hide certain Text elements from my content? HTML: <div id="name"> Attempting to hide specific Text elements from content. </div> Desired outcome: <div id="name"> Attempting to hide <p st ...

What causes an infinite loop in my app when passing a prop, and why doesn't it update the prop as expected?

Trying to pass a single variable from one component to another should be simple, but it's turning out to be more complicated than expected. I have a Search bar in one component and I want the input from that search bar to display in another component. ...

A plethora of unhandled DOMException errors found in a basic Vue.js application

I have been working on a Vue.js project for learning purposes, incorporating Quasar and Vuex. However, I keep encountering numerous Uncaught (in promise) DOMException errors which appear in the console. The application seems to work fine, but these red err ...

Experiencing the 'Page prerendering error' message within Next.js

I encountered a prerender error during the deployment phase that I'm struggling to comprehend: Error occurred prerendering page "/about". Read more: https://nextjs.org/docs/messages/prerender-error ⨯ useSearchParams() should be wrapped in ...

The UI does not reflect changes to the scope variable after it is updated by a service call

When I add a new item to the scope from another service, the select tag options that come from the service do not reflect the newly inserted value immediately. The new option only appears after refreshing the page. It seems like the scope is not updating t ...

AngularJS: customizing table columns on the fly

I need to customize the display of certain columns in a table based on the JSON response I receive from the server. Here is an example of the HTML code: <div ng-controller='browserStatsController'> <select id="searchTypeDropdown" name= ...

Tips for fetching a particular item from a getItem dynamoDB in JavaScript

I am trying to retrieve an item from my AWS database. The item 'test2' is printing correctly in my console. However, I want to extract an attribute or variable from this item and store it as a variable named test. How can I accomplish this? For i ...

Turn off the nicescroll scroll bar that appears as a default feature

Is there a way to disable the nicescroll scroll bar that appears in red by default on my html page? It's causing issues with zooming in and breaking the layout. ...

Clickable link in popup window using fancybox

When I try to use fancybox to open an iframe and scroll to an anchor tag, it works perfectly in IE but not consistently in other browsers. It stops at a different place than the anchor. I suspect the issue may be related to JavaScript based on information ...

How to customize XMLHttpRequest in Firefox's WebExtension

Recently, I've been attempting to override the XMLHttpRequest.protype.open method within Firefox's WebExtension environment. My current approach involves the following code snippet written in a content script: var oldOpen = XMLHttpRequest.protot ...

ng-tourguide component for navigating through multiple screens

Currently, I am utilizing Angular JS to develop my project. One requirement I have is to implement a tour guide that navigates through multiple pages and displays the next step upon clicking the next button. I have successfully incorporated ng-walkthrough ...

Is there a way to adjust this angular2 service to make it slightly more synchronous?

My goal is to create an Angular2 service that performs the following tasks: FTP to a remote server Read certain lines from a file Create a 'results' JSON object and return it to the component that called the service I have successfully impleme ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

Encountered an unhandled promise rejection: TypeError - The Form is undefined in Angular 6 error

Whenever I attempt to call one .ts file from another using .Form, I encounter the following error: Uncaught (in promise): TypeError: this.Form is undefined The file that contains the error has imported the .ts file which I intend to pass values to. ...