Search code examples
javascriptangularjsangularjs-ng-repeatng-class

Dynamic classes using ng-repeat in AngularJS


This is not a duplicate.

In the other post, they are just doing a ternary operation. I wanna changes classes within ng-repeat.

I have this piece of code with little bugs.

HTML:

<div id="server-id-list-container" class="panel-body col-md-12 scrollbar">
    <div class="server-id-list-element" ng-class="serverIdLength > 12 ? 'col-md-3' : 'col-md-2'" ng-repeat="server in selection.serverIds">
        <p class="alert alert-info">{{server.serverId}}<span ng-click="removeServerId($index)" class="glyphicon glyphicon-remove"></span></p>
    </div>
</div>

Controller:

_.forEach($scope.selection.serverIds, function(a) {
    $scope.serverIdLength = a.serverId.length;
});

Scope Object:

[
    {
        "serverId": "loma1pwipdb2002",
        "serverName": "",
    },
    {
        "serverId": "shdmqprtp1",
        "serverName": "",
    }
]

When I enter "loma1pwipdb2002", the class becomes col-md-3 and since I am using ng-repeat applies for all elements. I want the class to be applied only to serverIdLength > 12 and if its lesser than 12, col-md-2 should get applied.

Please advice.


Solution

  • Is it correct that you want to switch your class for each element of selection.serverIds list separately based on serverId string length? Need to know your selection.serverIds, is it your "Scope Object"? If yes, then I would do just

    <div 
      class="server-id-list-element"
      ng-repeat="server in selection.serverIds"
      ng-class="server.serverId.length > 12 ? 'col-md-3' : 'col-md-2'"> ... </div>
    

    The problem is that your $scope.serverIdLength is being calculated once for all the list. While you want to have a dynamic class based on each item specific property.

    Let's continue discussion if I didn't understand the issue and the entry conditions.