AngularJS - Conditionally apply style using ng-style to first element in ng-repeat

坚强是说给别人听的谎言 提交于 2019-12-11 09:27:13

问题


I have an object of styles and I need to set another css style only for the first element. I created a directive especially for that, but it doesn't work

I will appreciate your help!

Here is the code:

<div class="row" ng-style="rowCss" ng-repeat="top in gridObj" ng-zero>
$scope.rowCss = {
    "height" : rowAndSquareHeight,
    "padding-top": baseLine
}

editorApp.directive('ngZero', ['$document', '$parse', function($document, $parse) {
    return function(scope, element, attr) {
        $(element).css({"padding-top" : "0px"});
    };
}]);

Thanks!


回答1:


<div class="row" 
    ng-style="{ true : rowCss }[$first]" 
    ng-repeat="top in gridObj">
    ...

Plunker




回答2:


You don't need a directive for that. ng-repeat scope exposes an property $first in the repeat scope which is true for first element. You can define a class for the first row and use ng-class to apply it

ng-class="{'my-first-class':$first}"




回答3:


You can use $index to track the 'n'th element. Not sure if the directive has been created to solve this issue but could just use ng-attr-style="{$index==1 ? '"padding-top" : "0px"}'}"

Also you should not manipulate HTML or refer to presentation/css in Controllers.




回答4:


you can use the ng-if - new in version 1.1.5, for manipulating CSS styling conditionally.



来源:https://stackoverflow.com/questions/25176185/angularjs-conditionally-apply-style-using-ng-style-to-first-element-in-ng-repe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!