在angularjs中排序或重新排列表格的行(拖放)

Sus*_*rut 26 javascript html-table angularjs angularjs-directive

我想要在表格中重新排列行的功能(使用拖放操作排序行). 行排列的索引也应该在模型中改变.

我怎样才能做类似的事情:http://jsfiddle.net/tzYbU/1162/ 使用Angular Directive?

我正在生成表格:

<table id="sort" class="table table-striped table-bordered">
  <thead>
    <tr>
      <th class="header-color-green"></th>
      <th ng-repeat="titles in Rules.Titles">{{titles.title}}</th>
    </tr>
  </thead>
  <tbody ng-repeat="rule in Rules.data">
    <tr>
      <td class="center"><span>{{rule.ruleSeq}}</span></td>
      <td ng-repeat="data in rule.ruleData">{{statusArr[data.value]}}</td>
    </tr>
  </tbody>
</table>
Run Code Online (Sandbox Code Playgroud)

Sus*_*rut 48

我做的.请参阅下面的代码.

HTML

<div ng:controller="controller">
    <table style="width:auto;" class="table table-bordered">
        <thead>
            <tr>
                <th>Index</th>
                <th>Count</th>
            </tr>
        </thead>
        <tbody ui:sortable ng:model="list">
            <tr ng:repeat="item in list" class="item" style="cursor: move;">
                <td>{{$index}}</td>
                <td>{{item}}</td>
            </tr>
        </tbody>{{list}}
        <hr>
</div>
Run Code Online (Sandbox Code Playgroud)

指令(JS)

var myapp = angular.module('myapp', ['ui']);

myapp.controller('controller', function ($scope) {
    $scope.list = ["one", "two", "thre", "four", "five", "six"];
});

angular.bootstrap(document, ['myapp']);
Run Code Online (Sandbox Code Playgroud)

  • 知道如何在没有纯粹Angular.js的jQuery的情况下处理这个问题吗? (11认同)

Tho*_*mas 11

还有另一个库:RubaXa/Sortable:https://github.com/RubaXa/Sortable

它适用于现代浏览器,没有jQuery依赖.包括角度指令.我现在要去检查一下.

您还可以获得良好的触摸支持.

  • 似乎为我工作.确保将指令放在TBODY元素> http://jsbin.com/gebirenoje/1/edit?html,js,output (3认同)

joh*_*cky 5

AngularJS并非真正构建用于操作 DOM元素,而是扩展页面的HTML.

请参阅此问题维基百科条目.

对于DOM操作,jQuery/mootools/etc会很好地适应你(提示:jsFiddle链接中的示例).

您可以使用AngularJS来跟踪元素的排序以更新模型.我不知道如何使用指令执行此操作,但以下代码可能很有用

var MyController = function($scope, $http) {
    $scope.rules = [...];
    ...

}

var updateRules = function(rule, position) {
    //We need the scope
    var scope = angular.element($(/*controller_element*/)).scope(); //controller_element would be the element with ng-controller='MyController'

    //Update scope.rules
}
Run Code Online (Sandbox Code Playgroud)

然后,当您重新排序列表时,只需updateRules()使用更改的规则及其在模型中的新位置进行调用.