简体   繁体   中英

Remove click event on last item in ng-repeat

I have an ng-repeat which looks like the following:

<ol>
    <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">{{node.name}}</li>
</ol>

This is great and gives me an <ol> with <li> 's generated from myArray .

However, I want the last item in my ng-repeat to not have the ng-click event, or at least have it disabled. For example:

<ol>
     <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">Step 1</li>
     <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">Step 2</li>
     <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">Step 3</li>
     <li class="pointer node-name" ng-click="myClick(node)" ng-repeat="node in myArray">Step 4</li>
     <li class="pointer node-name" ng-repeat="node in myArray">Step 5</li>
    </ol>

Is this even possible? Thanks.

You can use the $last -Property within the ngRepeat to check if it is the last element. Then just place a condition inside your clickhandler...

<li class="pointer node-name" ng-click="myClick(node, $last)" ng-repeat="node in myArray">Step 5</li>

You can use $index to see with index of the loop into myArray, [0 .. n-1]. And then when $index == myArray.length -1 you can disable the ng-click.

It should be easy enough to disable it.

<ol>
    <li class="pointer node-name" ng-click="myClick(node)" ng-disabled="$last" ng-repeat="node in myArray">{{node.name}}</li>
</ol>

or check if the index is equal to the length of the array minus 1 (last element)

<ol>
    <li class="pointer node-name" ng-click="myClick(node)" ng-disabled="$index === myArray.length - 1" ng-repeat="node in myArray">{{node.name}}</li>
</ol>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM