Sagi Mann
Sagi Mann

Reputation: 3620

how to set clicked list item in angularJS?

I have a set of list items, each is clickable. Upon click, I want the underlying model to update to the currently clicked list item index. For example, if I click on the third item, I want my controller's $scope.current to be set to 2. Since the list items aren't standard form inputs, I cannot seem to use ng-model, so I was wondering what's the solution....

Upvotes: 0

Views: 3204

Answers (1)

Ori Drori
Ori Drori

Reputation: 193012

You can use a method attached to $scope, and pass $index (the current item ngRepeat index) to it:

$scope.items = ['one', 'two', 'three', etc...];

$scope.current = null;

$scope.setCurrent = function setCurrent(index) {
    $scope.current = index;
};

<ul>
    <li ng-repeat="item in items" ng-click="setCurrent($index)">{{item}}</li>
</ul>

Upvotes: 1

Related Questions