Dancia Dancia - 4 months ago 14
AngularJS Question

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.

Answer

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);
});