Search code examples
angularjsclicklistitemangular-ngmodel

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....


Solution

  • 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>