简体   繁体   English

选择angularjs ng-repeat中的第一个元素

[英]select first element in angularjs ng-repeat

I have a ng-repeat populating li tag. 我有一个ng-repeat填充li标签。 I want by default first element should be clicked and a function should be fired. 我希望默认情况下应单击第一个元素并应触发一个函数。 how can I do this using ng-repeated. 我该如何使用ng-repeated。 I tried ng-if and ng-switch. 我尝试了ng-if和ng-switch。 but other than first element rest are not getting populated. 但是除了第一个元素其余部分之外,其他所有元素均未填充。

html: 的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 . 使用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. ngInit的唯一适当用法是为ngRepeat的特殊属性设置别名。 You should use controllers rather than ngInit to initialize values on a scope. 您应该使用控制器而不是ngInit来初始化作用域上的值。

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. 它将对数组/对象的第一次迭代执行getViewsByColors函数。 You don't need to use ng-if in this case. 在这种情况下,您无需使用ng-if It will not work for the rest of your values. 它不适用于其余的价值观。 ` `

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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