使用jquery将类添加到ng-repeat中的第一个项目

dev*_*r87 8 javascript jquery angularjs

我是复杂指令的新手,我试图在jquery的ng-repeat中添加一个类(不幸的是我的项目正在使用它),就像在指令的控制器中一样:

   var highlightFirst = function(){
      $('.pointer').find('.fa-angle-down-first').next().addClass('boldit');
      console.log('in here')
    }

    highlightFirst();

    //also tried this:
    angular.element(document).ready(function(){
      $('.pointer').find('.fa-angle-down-first').next().addClass('boldit');
      console.log('in here')
    });
Run Code Online (Sandbox Code Playgroud)

我立刻调用了这个函数.什么都没发生.

当我$('.pointer').find('.fa-angle-down-first').next().addClass('boldit'); 在chrome dev工具中运行时,我想要加粗的实际上是粗体...我错过了什么让这个特定的解决方案工作?什么是最好的角度方式来做到这一点?

Lou*_*eda 18

你实际上并不需要jquery,并且应该避免在角度应用程序中尽可能多地使用jquery,你应该使用ng-class$ first这里的工作演示

<ul>
    <li ng-repeat="item in items" ng-class="{'fooClass': $first}">{{ item }}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

好处$first是当你排序ng-repeat它仍然可以正常工作.


Jer*_*son 11

只需使用ng-class:

<ul>
    <li ng-repeat="item in items" ng-class="{'myClass': item == items[0]}">{{ item.property }}</li>
</ul>
Run Code Online (Sandbox Code Playgroud)

编辑:链接到更多详细信息

https://docs.angularjs.org/api/ng/directive/ngClass