简体   繁体   中英

select first element in angularjs ng-repeat

I have a ng-repeat populating li tag. I want by default first element should be clicked and a function should be fired. how can I do this using ng-repeated. I tried ng-if and ng-switch. but other than first element rest are not getting populated.

html:

<ul id = "colors">
    <li ng-repeat="color in colors | filter:query" >
        <div style="background-color : {{color.color}}; height : 20px; width : 20px;" ng-if = '$first' ng-click="getViewsByColors(color)">
        </div>
    </li>
</ul>

Use ng-init . Your click event will not trigger in that manner. According to the doc

The only appropriate use of ngInit is for aliasing special properties of ngRepeat. You should use controllers rather than ngInit to initialize values on a scope.

Your snippet will look like

<div style="background-color : {{color.color}}; height : 20px; width : 20px;" ng-init="($first) ? getViewsByColors(color) : ''">

It will execute the getViewsByColors function for first iteration of your array/object. You don't need to use ng-if in this case. It will not work for the rest of your values. `

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