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

select first element in angularjs ng-repeat

本文关键字:第一个 元素 angularjs ng-repeat 选择      更新时间:2023-09-26

我有一个ng-repeat填充li标记。我希望在默认情况下,第一个元素应该被单击,一个函数应该被触发。怎么用n -repeat来做呢。我试了ng-if和ng-switch。但是除了第一个元素之外,其余的都没有被填充。

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>

使用ng-init。单击事件不会以这种方式触发。根据doc

ngInit唯一合适的用法是用于混叠特殊属性ngRepeat。你应该使用控制器而不是ngInit来初始化作用域的值。

你的代码片段看起来像

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

它将在数组/对象的第一次迭代中执行getViewsByColors函数。在这种情况下,您不需要使用ng-if。它不会对你的其他价值观起作用。'