在表angularjs中更改单个单元格(td)的css

时间:2015-01-03 14:50:34

标签: javascript css angularjs

问题:使用AngularJS,我需要更改用户点击的单个单元格(td)的颜色(或者我们可以说是CSS)。

目前为了简化用例,只想更改所有表格单元格的颜色

下面是我尝试过的代码,但它改变了表格中所有单元格的颜色。

<body ng-controller="MainCtrl">
    <table>
      <tbody>
        <tr ng-repeat="row in tableType.data.rows track by $index">
          <td ng-repeat="col in row track by $index" >
            <span id={{col}} ng-class='cellColor' ng-click='updateCellColor(col)'>{{col}}</span>
          </td>
        </tr>
      </tbody>
    </table>
  </body>

位指示

app.controller('MainCtrl', function($scope) {
  $scope.tableType = {
    data: {
      rows: [
        ["69123", 20, 20, 40, 0, 0, 0, 0, 20, 20, 20, 0, 20, 20, 0, 20],
        ["69121", 20, 20, 40, 0, 0, 0, 20, 20, 40, 20, 0, 20, 20, 0, 20],
        ["69124", 20, 20, 40, 0, 0, 0, 0, 0, 0, 20, 0, 20, 0, 0, 0],
        ["69221", 20, 20, 40, 20, 0, 20, 0, 0, 0, 20, 0, 20, 20, 20, 40]
      ]
    }
  };

  $scope.cellColor = "blue";

  $scope.updateCellColor = function(col){
    if(parseInt(col)===parseInt(0)){
        alert('changing color to red');
        $scope.cellColor = "red";
    }else{
        alert('changing color to yellow');
        $scope.cellColor = "yellow";
    }
  };

});

CSS

.red{
    color:red;
}

.blue{
    color:blue;
}

.yellow{
    color:yellow;
}

2 个答案:

答案 0 :(得分:0)

问题是您将所有单元格绑定到范围的cellColor变量的值。如果你想做你想做的事情,那么一个解决方案是创建一个指令,你应用于每个具有自己的cellColor变量的单元格,该变量覆盖从回调为的父作用域继承的变量。调用。

答案 1 :(得分:0)

这是另一个带有直接处理DOM的指令的解决方案。

HTML

<body ng-app="app">
  <div ng-controller="MainCtrl">
    <table>
      <tbody>
        <tr ng-repeat="row in tableType.data.rows track by $index">
          <td ng-repeat="col in row track by $index" >
            <span id={{col}} highlight-on-click>{{col}}</span>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</body>

指令

app.directive('highlightOnClick', function(){
  return {
    restrict: 'A',
    link: function($scope, element){
      element.bind('click', function(){
         if(parseInt(element.text()) === 0){
           element.toggleClass('red');
         } else {
           element.toggleClass('yellow');
         }   
      })
    }
  }

工作样本here