Search code examples
angularjsng-class

ng-class does not apply when expression re-evaluates


This code is from an offline network so I can't paste it here. I'm summarizing it.

I have the following code:

<tr ng-repeat="agent in agents" ng-class="agent.getClass()">
   <td>{{agent.server}}</td>
   <td>{{agent.status}}</td>
</tr>

The agents list is loaded via ajax requests.

app.js:

angular.module('agentsApp', [])

.controller('agentsController', function($scope, $http, $interval) {

    $scope.agents = {};
    $interval(function() {
       $http.get('/AgentsServlet').success(function(data) {
            angular.forEach(data, function(agent) {
                $scope.agents[agent.server] = new Agent(agent.server, agent.status);
            });
       });
    }, 1000);
});

Agent.js

var Agent = function(server, status) {
    this.server = server;
    this.status = status;
}

Agent.prototype.getClass = function() {
     return {
         success: this.status === 'RUNNING',
         error: this.status === 'ERROR'
     };
}

For the record, the AgentsServlet load agents and their data from a simple text file.

Now, when I change the file contents, the next ajax request will successfully load and update the table's contents BUT, the ng-class is not changed. For example, if I change an agent's status from RUNNING to ERROR, its tr's class does not change to 'error'.

The weird thing is that if I put inside the ng-class the getClass() logic, it works, eg:

<tr ng-repeat="agent in agents" 
    ng-class="{success: agent.status==='RUNNING', error: agent.status==='ERROR'}">
   <td>{{agent.server}}</td>
   <td>{{agent.status}}</td>
</tr>

It seems that the function call is the problem and not the expression.. Any ideas?

Thanks


Solution

  • html:

    <tr ng-repeat="agent in agents" ng-class="agent.cssClass" >
       <td>{{agent.server}}</td>
       <td>{{agent.status}}</td>
    </tr>
    

    js:

    function agent(server, status) {
    
        this.server = server;
        this.status = status;
    
        this.cssClass = this.status ==='RUNNING'? 'success':'error';
      }
    
    
    
    var app = angular.module('app', []);
    
    app.controller('MainCtrl', function($scope) {
      $scope.agents = [];
    
      var a1 = new agent(1, "RUNNING");
      var a2 = new agent(2, "ERROR");
      $scope.agents.push(a1);
      $scope.agents.push(a2);
    
    });