I have created a plunker with my current code .. plunker
When one of the buttons on each item is clicked i want that 'li' element to get the class selected (thats is have its background changed to grey. and if another element is clicked i want the previous items selected class to be removed and added to the clicked item. so basically a toggle of the class.. )
I have already tried to achieve it by using the $index :
$scope.isClicked = function(index){
$scope.selected = index;
};
and in the items.tpl.html toggle it :
<li class="item" ng-class"{selected: index===selected}">
what am i doing wrong here? Can someone please help ...
See forked plnkr
In a nutshell, you're are using ng-repeat
for the directive user-group-item
. For each repeated user-group-item
(2 in this case), the directive will make its own scope and controller method initialization. So you can not use $scope.selected
inside the directive to store what is selected, because each user-group-item
will have its own selected
variable in its $scope
You need to store that selected state outside the directive, ie in the main controller. I created a function setSelected
in the main controller and passed it as a method reference using &
in the directive. Inside the $scope.isClicked
method, you need to refer to the parent scope to get the function setSelected