0

I am new to angular. I am trying to make a menu with several categories.

The categories are defined as <li>...</li> tags. When a user selects one category, I highlight it (and un-highlight the previously selected element).

So far, I used a combination of ng-repeat/ng-click :

<ul class="nav nav-sidebar">
  <li data-ng-repeat="category in categories" class="menu-element ng-scope" data-category="{{category.category}}"  data-ng-click="onClick($event)">
      <a href="#" class="glyphicon glyphicon-{{category.icon}}"> {{category.text}}</a>
  </li>
</ul>

And the controller :

var myApp = angular.module('myApp', []);
myApp.controller('categoryListCtrl', function ($scope) {

  $scope.onClick = function(event) {
    //What must I do here?
    console.log(event);
  };

  $scope.categories = [
    {'category': 'home',       icon :'home',     text: 'Home'},
    {'category': 'news',       icon :'comment',  text: 'News'},
    {'category': 'brands',     icon :'tower',    text: 'Brands'},
    [...]
  ]
}

When the user clicks on a <li> element, the function $scope.onClick is executed.

Here, I would like to add a "highlight" class to the selected <li> and remove the "highlight" class from the previously selected <li>.

Looking at console.log(event), I see that event.toElement is the <a> that was clicked.

Still looking at console.log(event) , I see that I can get the <li> element by using event.toElement.offsetParent but this is DOM manipulation and I have been told that it was evil in a controller.

Question : I put the ng-click directive on the <li> element, why do I get the <a> element in event.toElement?

Question : What is the "most angular" way to highlight/un-highlight elements?

1 Answer 1

1

The key is to keep track of a selected index when you handle the click and then conditionally apply an active class to the element if its index value matches the trapped selected index value.

Better explained in this answer here

Sign up to request clarification or add additional context in comments.

1 Comment

I have used the same approach in my own app recently which consists of a list of items and when their sort order changes the selected item correctly stays so

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.