1

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

3
  • This code seems incomplete to understand your context.. Can you share executable demo/snippet or JSFiddle ? Create a Minimal, Complete, and Verifiable example Commented Jul 15, 2016 at 16:42
  • As @Rayon stated we need to know the context in order to assist. e.g. are these paragraphs being generated in a ngRepeat?? Commented Jul 15, 2016 at 16:47
  • Possible duplicate of AngularJs toggle ng-class ng-click Commented Jul 15, 2016 at 16:47

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Pleasure is mine :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.