J D
J D

Reputation: 1818

AngularJS - Apply a class onclick and keep it applied, or remove when clicked again

I am applying a class on onclick to my custom element, and I want to keep it applied. Like there are bunch of <event> elements, and when I click on some other element, the previous element loses that selected class. That is I cannot get it to apply the selected class to more than one class at a time.

Here is my view code:

<event class="event" ng-repeat="event in events" event="{{ event }}"
       ng-class="{'selected' : $index == selected}"
       ng-click="selectEvent($index, event)">
    {{ event }}
</event>

And here is my controller

myApp.controller('MyCtrl', function ($scope, $http) {
    $scope.selectEvent = function($index, event) {
        $scope.selected = $index;
        console.log(event);
    }
});

Additionally, I would also like for the class to be removed to when the particular <event> is clicked again.

Upvotes: 0

Views: 483

Answers (1)

Chris
Chris

Reputation: 7278

You've only got one piece of data ($scope.selected) tracking selection. Every time a new element is clicked, the previous selection is overwritten.

If you want each event to have a separate selected/not-selected state, you have to create a data structure that allows that.

In this fiddle, I defined events as:

    $scope.events = [
        {name: 'event1', selected: false},
        {name: 'event2', selected: false},
        {name: 'event3', selected: false}
    ];

And I think it works as you intended.

Upvotes: 1

Related Questions