pass button id in ng-click angular.js
Asked Answered
P

2

14

I need to pass button id in Ionic Framework.

Here is what I have tried.

In js code:

angular.module('todo', ['ionic'])
.controller('TodoCtrl', function($scope) {
    {
        $scope.showAlert = function(btnId) {
            alert(btnId);
        };
    }
});

In html:

<button id="a" class="button button-light"  data="{{button.id}}" ng-click="showAlert(data.id)">
    Click Me
</button>

O/P: undefined

or

<button id="a" class="button button-light"  data="{{button.id}}" ng-click="showAlert(data)">
    Click Me
</button>

O/P: undefined

or

<button id="a" class="button button-light"  data="{{event.id}}" ng-click="showAlert(data.id)">
    Click Me
</button>

O/P: undefined

or

<button id="a" class="button button-light" ng-click="showAlert(this.id)">
    Click Me
</button>

O/P: undefined

or

<button id="btnId" class="button button-light" ng-click="showAlert('btnId')">
    Click Me
</button>

O/P: btnId

Is this correct way to directly write id of button in function?

I referred to a few answers like this. So I think I am making some mistake in using it. Please let me know what I need to change.

Patronize answered 25/3, 2014 at 9:31 Comment(2)
The event that's referred to in the answer you've linked isn't working for you because it's setup outside the button in the surrounding ng-repeat div <div class="row" ng-repeat="event in events">Orthodox
have you seen this jsfiddle.net/jandersen/RUnaE ?Seldon
A
46

Yo, check this gist:

https://gist.github.com/lc-nyovchev/ed0a640a82a0f2dfd5a1

That is a very easy and naive way to do it.

<div data-ng-init="btnId='asd';">
    <button data-ng-attr-id="btnId" class="button button-light" data-ng-click="showAlert(btnId)">
        Click Me
    </button>
</div>

Or you can have in your controller:

$scope.btnId = 'asd'; 

Then you don't need the ng-init block div.

Or you can get a handle to the $event in your ng-click, and get its target, and then get its id, but I wouldn't recommend that, it is not the angular way of doing things:

<button id="bla" class="button button-light" data-ng-click="showAlert($event)">
    Click Me
</button>


$scope.showAlert = function(event){
    alert(event.target.id);
}
Athapaskan answered 25/3, 2014 at 9:42 Comment(0)
W
3

This works if no repeaters are there , if repeaters are the data attribute should have different names and secondly event.CurrentTarget.Id will make it work.

White answered 9/10, 2015 at 15:14 Comment(1)
$scope.showAlert function definition should be inside the controller. It took me a while to figure it out.Mcnamara

© 2022 - 2024 — McMap. All rights reserved.