angularjs - 通过更新其他列表条目来更改列表的顺序

时间:2017-09-12 11:13:01

标签: javascript jquery angularjs

我有一个包含3个条目的键/值列表,例如

0,Value1

1,Value2

2,Value3

3,Value4

如果我将2更改为0,则索引为2的条目应滑移到位置0,附加元素将滑动到后面的位置。

例如,从0-1-2-3将是2-0-1-3

HTML

<div ng-controller="MyCtrl">
  <div class="row-sort" ng-repeat="(key1, value1) in selectList">
    <select class="row-select">
      <option ng-repeat="(key2, value2) in selectList" value={{key2}} ng-selected="key1 == key2">{{key2}}</option>
    </select>
    <span class="row-label">{{value1.name}}</span>
  </div>
</div>

的JavaScript

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

function MyCtrl($scope) {
  $scope.selectList = [{
    idx: 0,
    name: 'Value1'
  }, {
    idx: 1,
    name: 'Value2'
  }, {
    idx: 2,
    name: 'Value3'
  }, {
    idx: 3,
    name: 'Value4'
  }]
}

JS Fiddle Link

编辑1:它可以像jQuery Sortable Plugin一样工作,但只能使用Select-Boxes ... Jquery Sortable

任何人都知道如何使用AngularJS正常工作并纠正错误?

它是Angular UI Grid(重新排序列)所必需的

非常感谢!

1 个答案:

答案 0 :(得分:0)

您可以添加到列表selected键,将其绑定到ng-model以供选择并使用orderBy

$scope.selectList = [{
    idx: 0,
    selected: '0',
    name: 'Value1'
  }, {
    idx: 1,
    selected: '1',
    name: 'Value2'
  }, {
    idx: 2,
    selected: '2',
    name: 'Value3'
  }, {
    idx: 3,
    selected: '3',
    name: 'Value4'
  }];

HTML

<div class="row-sort" ng-repeat="(key1, value1) in selectList | orderBy : 'selected'">
    <select class="row-select" ng-model="value1.selected">
      <option ng-repeat="(key2, value2) in selectList" 
              value={{key2}}>{{key2}}</option>
    </select>
    <span class="row-label">{{value1.name}}</span>
  </div>

修改

您可以编写观察者并替换项目的位置:

$scope.$watch(function () {
        return $scope.selectList;
    },
   function (newVal, oldVal) {

     var selectedItemId;
     var selected;
      angular.forEach($scope.selectList, function(item){
          if(item.idx !== parseInt(item.selected)){
            selectedItemId = item.idx;
            selected = item.selected;            
            }         
      });

      angular.forEach($scope.selectList, function(item){
          if(item.selected === selected){
            item.selected = ''+selectedItemId;
            item.idx = selectedItemId;
            selectedItemId = undefined;
            selected = undefined;
            }   

            if(item.idx !== parseInt(item.selected)){
              item.idx = parseInt(item.selected);
            }
      });      
    },true);

Demo Fiddle 2