Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing the current HTMLElement to ng-click

Is it possible to pass the HTMLElement to a ng-click configured on a controller?

Here's some sample code:

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

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:

Don´t get confused, I said that I want get the whole element not only the id from the model.

$event.target - don't works in some versions of IE.

like image 516
Filipe Avatar asked Mar 12 '14 12:03

Filipe


People also ask

What does ng-click mean?

Definition and Usage The ng-click directive tells AngularJS what to do when an HTML element is clicked.

What is the difference between Ng-click and Onclick?

Another significant difference between ng-click and onclick is the execution context. Code inside an onclick attribute executes against the global window object, while an expression inside of ng-click executes against a specific scope object, typically the scope object representing the model for the current controller.

What is the use of ng-click in AngularJS?

The ng-click Directive in AngluarJS is used to apply custom behavior when an element is clicked. It can be used to show/hide some element or it can pop up an alert when the button is clicked.

How to hide and show using Angular js?

The ng-hide directive in AngularJS is a function using which an element will be hidden if the expression is TRUE. If the Expression is FALSE, the element will be shown. In the background, the element is shown or hidden by removing or adding the . ng-hide CSS class onto the element.


1 Answers

The HTML:

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

And the js:

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);
  }
like image 150
CodePrimate Avatar answered Sep 24 '22 03:09

CodePrimate