Donovant
Donovant

Reputation: 3161

Angularjs - How can it point to all the ng-repeat from on of them by a ng-click?

What can I do to point to the other ng-repeat elements from the ng-click function? I would like to modify the {{nameClass}} of the other ng-repeat elements from a click to someone of them.

Html:

<li class="{{nameclass}}" ng-repeat="person in people" ng-click="somefunction()"></li>

javascript:

function somefunction(){
     this.nameclass = "some";
     //what to set the other classes???
}

Upvotes: 0

Views: 73

Answers (4)

ReedD
ReedD

Reputation: 997

You could also utilize ng-class and have that set some boolean to enable a given class on whatever objects you want.

In your controller

$scope.someFunction = function (){
    $scope.active = true;
}
$scope.someOtherFunction = function (){
    $scope.loading = true;
}

In your HTML

<li ng-class="{activeClass: active, someOtherClass: loading}" ng-repeat="person in people" ng-click="somefunction()"></li>

What this does is add "activeClass" to the class definition when "active" is true. I added a second one "someOtherClass" to further illustrate this example.

Upvotes: 1

SimonVanCasteren
SimonVanCasteren

Reputation: 117

I believe this is what you're looking for:

<li ng-class="{true: 'someOther'}[$index!=selectedIndex]" 
    ng-repeat="person in people" ng-click="somefunction($index)">{{person}}</li>

$scope.people = ['Peter','Paul','Mary'];
$scope.selectedIndex = 0;
$scope.somefunction = function(index) {
  $scope.selectedIndex=index;
};

In Plunker:

http://plnkr.co/edit/2IsD2W3YclUe0Bc5Q93a?

  1. When you click on an item, the index of this item is set as the selectedIndex property on the scope.
  2. All items which index does not equal this selectedIndex gets the class 'someOther' applied to it.

Full explanation of the expression in ng-class:

https://stackoverflow.com/a/18126926/2331058

Upvotes: 0

goutham
goutham

Reputation: 240

You can pass in the class you want to set into the function on ng-click.see this plunk http://plnkr.co/edit/oXavr7CVTpPfPUZJO0f9?p=preview

Upvotes: 2

dfsq
dfsq

Reputation: 193261

If your goal is to set the same class value to all the items then you should use $scope.nameclass:

function somefunction(){
    $scope.nameclass = "some";
}

And the different is that when you use this.nameclass you set nameclass property of the current item scope, not the parent scope all items belong to. When you set it to $scope object then all the LI items inherit nameclass not only clicked one.

Upvotes: 0

Related Questions