表达式重新计算时,ng-class不适用

时间:2014-06-24 14:20:43

标签: angularjs ng-class

此代码来自离线网络,因此我无法将其粘贴到此处。我正在总结它。

我有以下代码:

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

agents列表是通过ajax请求加载的。

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

对于记录,AgentsServlet加载代理及其来自简单文本文件的数据。

现在,当我更改文件内容时,下一个ajax请求将成功加载并更新表的内容但是,ng-class不会更改。 例如,如果我将代理的状态从RUNNING更改为ERROR,则其tr的类不会更改为“error”。

奇怪的是,如果我在ng-class中放入getClass()逻辑,它就可以工作,例如:

<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>

似乎函数调用是问题,而不是表达式.. 有什么想法吗?

由于

2 个答案:

答案 0 :(得分:0)

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

});

答案 1 :(得分:0)

请尝试:plunkr

功能代理(服务器,状态){

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



});

<!DOCTYPE html>
<html ng-app="app">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link href="style.css" rel="stylesheet" />
    <script data-semver="1.2.17" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.17/angular.min.js" data-require="angular.js@1.2.x"></script>
    <script src="app.js"></script>
  </head>

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

</tr>
</table>
  </body>

</html>