Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting attribute of element in ng-click function in angularjs

I have a span tag like below which call a function in the controller when clicked.

HTML

<div class="row" ng-repeat="event in events">     <div class="col-lg-1 text-center">         <span class="glyphicon glyphicon-trash" data={{event.id}} ng-click="deleteEvent()">         </span>     </div> </div> 

Controller

$scope.deleteEvent=function(){     console.log(this); } 

I need to get the value in data attribute in the controller function. I tried using this keyword and $event; neither one worked.

Please help.

like image 326
Saravanan Avatar asked Aug 03 '13 04:08

Saravanan


People also ask

What is Ng-click in AngularJS?

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 $$ in AngularJS?

The $ in AngularJs is a built-in object.It contains application data and methods.

What is Ng ATTR?

ng-attr is used for add or not the attribute in context. If the expression {{undefined || null}} , the attribute is not added otherwise if has a value then attribute is added with the value {{ value }} . The most common cases is in interpolation.


2 Answers

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a> 

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value; 

Which would return exampleData.

Here's a full jsFiddle.

like image 195
Brett DeWoody Avatar answered Oct 16 '22 11:10

Brett DeWoody


Try passing it directly to the ng-click function:

<div class="col-lg-1 text-center">     <span class="glyphicon glyphicon-trash" data="{{event.id}}"           ng-click="deleteEvent(event.id)"></span> </div> 

Then it should be available in your handler:

$scope.deleteEvent=function(idPassedFromNgClick){     console.log(idPassedFromNgClick); } 

Here's an example

like image 28
jandersen Avatar answered Oct 16 '22 10:10

jandersen