Dancia
Dancia

Reputation: 812

Change color of li element based on array of strings

In my view I have list of statuses.

<ul>
    <li>FIRST_STATUS</li>
    <li>SECOND_STATUS</li>
    <li>THIRD_STATUS</li>
</ul>

In my model controller I retrieve updated statuses each second:

    $interval(function () {
            $scope.bad_statuses = Model.getStatuses({id: $scope.someModel.id});
    }, 1000);

$scope.statuses is an array of bad statuses, for example $scope.bad_statuses[0] = FIRST_STATUS. If status exists in $scope.bad_statuses, i want to color it red, otherwise - green.

So basically, somehow I need to retrieve each <li> value and based on condition if content from li existst in $scope.bad_statuses array, color it green or red.

How should I approach this problem? Im new to angularjs.

Upvotes: 2

Views: 168

Answers (2)

Jelmer
Jelmer

Reputation: 1009

I made a plunkr for you, this should work :)

https://plnkr.co/edit/OP66yUB5lxBS5uCmtbRh?p=preview

Javascript code:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope, $interval) {
  $scope.name = 'World';
  $scope.bad_statuses = ["FIRST_STATUS", "THIRD_STATUS"];
  $interval(function () {
            var lis = document.getElementById("list").getElementsByTagName("li");
            angular.forEach(lis, function(value, key){
               if($scope.bad_statuses.indexOf(value.innerHTML) > -1){
                 console.log("red");
                 value.style.color = 'red';
               }
               else{
                 console.log("green");
                 value.style.color = 'green';
               }
            });

  }, 1000);
});

Upvotes: 2

George Kagan
George Kagan

Reputation: 6124

<li ng-style="getColor(*status*)"></li>

In controller:

$scope.getColor = function(status) {
    return $scope.bad_statuses.indexOf(status) > -1 ? {color: 'red'} : {color: 'green'};
}

Documentation for ng-style directive.

Upvotes: 0

Related Questions