Clay Banks
Clay Banks

Reputation: 4581

Adding Classes to Elements using ng-click

I have a list of <p> tags in my Angularjs appication that I would like to set an active class on when any of them are selected using the ng-click directive

<p ng-click="setActive()">Paragraph 1</p>
<p ng-click="setActive()">Paragraph 2</p>
<p ng-click="setActive()">Paragraph 3</p>

I've read one of the best ways to toggle an active class is to push each applicable object into an array and set the class by the array index; is their a simpler way to do this using html elements?

Note* these paragraphs will be rendered dynamically to the DOM as a result of an AJAX request

Upvotes: 1

Views: 81

Answers (1)

Shintu Joseph
Shintu Joseph

Reputation: 962

Use ngClass directive for this

  $scope.setActive = function(currentEl){
    $scope.currentEl = currentEl;
  };
<p ng-class="{ 'active' : currentEl == 'p1' }" ng-click="setActive('p1')">Paragraph 1</p>
<p ng-class="{ 'active' : currentEl == 'p2' }" ng-click="setActive('p2')">Paragraph 2</p>
<p ng-class="{ 'active' : currentEl == 'p3' }" ng-click="setActive('p3')">Paragraph 3</p>

Upvotes: 1

Related Questions