GuillaumeRZ
GuillaumeRZ

Reputation: 2944

Get button name in angular

I'm trying to get the name of a button selected in a variable, and do something after (change the content of a <p>).

<form>
    <button name="paypal" class="moyen-payement-button" ng-class="{actif: actifSelected.selectedButton === 1}" ng-click="actifSelected.select(1)">
        <img src="images/payement-methods/paypal.svg" alt="Paypal" class="paypal" />
    </button>
    <button name="creditCard" class="moyen-payement-button" ng-class="{actif: actifSelected.selectedButton === 2}" ng-click="actifSelected.select(2)">
         <img src="images/payement-methods/credit-card.svg" alt="Carte de crédit" class="creditCard" />
    </button>
</form>

<p>Name of my button: </p>
<p>1</p>

The <p> with "1" have to change in "2" if the button creditCard is selected, I've find ng-show / ng-hide but I think I can simply modify the content of a <p> without creating another <p>?

Upvotes: 4

Views: 9527

Answers (4)

andyhasit
andyhasit

Reputation: 15319

You can pass $event to ng-click:

  <button name="hello" ng-click="myFunction($event, 2)">Test</button>
  <p>{{btnName}}</p>
  <p>{{arg1}}</p>

With this in the controller:

$scope.myFunction = function(e, arg1) {
  $scope.arg1 = arg1;
  console.log(e.target.name);
  $scope.btnName = e.target.name;
}

See this Plunkr

Upvotes: 1

Kelvin
Kelvin

Reputation: 690

You can use:

<button ng-click="actifSelected.select($event,1)"></button>

And in your controller, you can use $event to trigger element

$scope.actifSelected.select = function($event, value) {
    var button = angular.element($event.currentTarget);
    var buttonName = button.attr("name");
}

Upvotes: 4

brewsky
brewsky

Reputation: 617

Just display the selectedButton variable display in your

 <p>{{actifSelected.selectedButton}}</p>

Upvotes: 0

Alon Eitan
Alon Eitan

Reputation: 12025

You can use the following expression:

<p>{{ actifSelected.selectedButton === 1 ? '1' : '2' }}</p>

Upvotes: 3

Related Questions