Angular Js在表中交换列

时间:2017-08-02 12:35:37

标签: angularjs

我想在表格中交换2列。最后,我成功完成了更改,但只有数据。单元格的属性(样式,id,类)没有移动。我试图用jquery移动属性(我知道,不是一种优雅的方法),但它只是对症处理。单击数据重新加载按钮后,属性将恢复。 如何使用所有属性更改列顺序?

我的代码:https://codepen.io/qwertz_/pen/YxWMBO

<!DOCTYPE html>
<html>
<head>
  <title>angT</title>
  <script type="text/javascript" src="http://code.angularjs.org/angular-1.0.0rc10.js"></script>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <style>
  th, td{padding: 3px 20px;border: 1px solid red;}
  </style>
</head>
<body>

<div ng-controller="MyCtrl" ng-app="myApp">
  <button ng-click="swap(0)">first2second</button>
  <button ng-click="reload()">reload</button>

<table id="myTable" >
    <tr ng-repeat="row in ths">
        <th class="oo1">{{col(row, 0)}}</th>
        <th class="oo2">{{col(row, 1)}}</th>
        <th class="oo3">{{col(row, 2)}}</th>
        <th class="oo4">{{col(row, 3)}}</th>
    </tr>
    <tr ng-repeat="row in rows">
        <td class="o1" style="background-color:yellow;">{{col(row, 0)}}</td>
        <td class="o2" style="background-color:pink;">{{col(row, 1)}}</td>
        <td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
        <td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
    </tr>
  </table>
</div>

<script type='text/javascript'>
var myApp = angular.module('myApp',[]);
//myApp.directive('myDirective', function() {});
//myApp.factory('myService', function() {});
function MyCtrl($scope) {
  $scope.mycol = new Array();
  $scope.mycol[0] = 'id';
  $scope.mycol[1] = 'name';
  $scope.mycol[2] = 'db';
  $scope.mycol[3] = 'let';
  $scope.reload = function()
      {
          $scope.rows=[{id:parseInt(Math.random()*10000),name:"Liv","db":21,let:"r"},{id:parseInt(Math.random()*10000),name:"Mike",db:30,let:"u"}];
          };
  $scope.swap = function(i) {  

        var temp = $scope.mycol[i];
        $scope.mycol[i] = $scope.mycol[(i+1)];
        $scope.mycol[(i+1)] = temp;
  };
  $scope.col = function(row, mycol) {
      return row[$scope.mycol[mycol]];
  };
  $scope.reload();
  $scope.ths=[{id:"id",name:"name","db":"db",let:"letter"}];
}
</script>
</body>

很多

1 个答案:

答案 0 :(得分:0)

简单方法

您可以将颜色绑定到标题名称:

$scope.styles = {
   id: "yellow",
   name: "pink"
 };

和表格如下:

    <tr ng-repeat="row in rows">
          <td class="o1" ng-style="{'background-color':styles[mycol[0]]}">{{col(row, 0)}}</td>
          <td class="o2" ng-style="{'background-color':styles[mycol[1]]}">{{col(row, 1)}}</td>
          <td class="o3" style="background-color:green;">{{col(row, 2)}}</td>
          <td class="o4" style="background-color:blue;">{{col(row, 3)}}</td>
      </tr>

标题值更改后,颜色也会发生变化

Codepen DEMO

更复杂但通用

您可以通过将所有表替换为指令(标题+数据)并使用$compile重建所有HTML表来实现它。