How to set ngClick only for $ first element in ngRepeat?

How can I assign ng-click to $first element in ng-repeat? In the code below, doSomething() should only be called when you click on the first input. The rest of the inputs should not have ng-click handlers assigned. I found examples of using $first with an ng class or ng-show, but not with ng-click.

 <div ng-repeat="item in items"> <input type="checkbox" ng-click="doSomething()"/>{{item.name}} </div> 
+6
source share
3 answers

You can also use ngSwitch , which avoids creating all the handlers that you mentioned in your comment on the accepted answer:

 <div ng-repeat="item in items" ng-switch on='$first'> <input type="checkbox" ng-switch-when='true' ng-click="doSomething()"/> <input type="checkbox" ng-switch-when='false'/> {{item.name}} </div> 
+3
source

Try the following:

 <input type="checkbox" ng-click="$first && doSomething()"/>{{item.name}} 

working exam: http://jsfiddle.net/wLrYc/

+9
source

Semi-ugly solution: send $ first as doSomething () argument

 <div ng-repeat="item in items"> <input type="checkbox" ng-click="doSomething($first)"/>{{item.name}} </div> 

and then $ scope.doSomething (actualDoSomething) matters, just do it if trueDoSomething is true.

0
source

All Articles