2013-12-13 47 views
1

我在angularJS中很新,我有一个问题。发送两个列表之间的值

这是一个小提琴恢复我的问题:http://jsfiddle.net/ShengTi/RmFYv/

一切都很好,如果我发送的第一个值,并继续秩序。

dptRecep : 
[{"text":"Aube","pos":"1"},{"text":"Marne","pos":"2"},{"text":"Haute marne","pos":"3"},{"text":"Bouches du rhone","pos":"4"},{"text":"Aisne","pos":"5"},{"text":"Ain","pos":"6"},{"text":"Aude","pos":"7"}] 

但是,如果我发送第一个,然后第三个等..我的价值混乱我的数组。

dptRecep : 
[{"text":"Aube","pos":"1"},{"text":"Bouches du rhone","pos":"4"},{"text":"Marne","pos":"2"},{"text":"Haute marne","pos":"3"},{"text":"Aude","pos":"7"}] 

可能是我应该插入我的价值之间的其他......?

回答

0

你可以试试这个:

 <li ng-repeat="item in dpt | orderBy:order:false"> 
      <a href='' ng-click='goToLastList(item.pos)'> 
       {{item.pos}} - {{item.text}} 
      </a> 
     </li> 

     ... 

     <li ng-repeat="item in dptRecep | orderBy:order:false"> 
      <a href='' ng-click='goToFirstList(item.pos)'> 
       {{item.pos}} - {{item.text}} 
      </a> 
     </li> 

,然后找到POS数组的位置:

在每次发送只有一个属性pos价值:

$scope.goToLastList = function (pos) { 
    var idx = getIndexByPost($scope.dpt, pos) 
    $scope.dptRecep.push($scope.dpt[idx]); 
    $scope.dpt.splice(idx, 1); 
}; 

$scope.goToFirstList = function (pos) { 
    var idx = getIndexByPost($scope.dptRecep, pos) 
    $scope.dpt.push($scope.dptRecep[idx]); 
    $scope.dptRecep.splice(idx, 1); 
}; 

function getIndexByPost(array, pos) { 
    var rindex = 0 
    array.forEach(function(element, index) { 
     if (element.pos == pos) rindex = index; 
    }); 
    return rindex; 
}; 

兼容性Array.prototype.forEach()

if (!Array.prototype.forEach) { 
    Array.prototype.forEach = function (fn, scope) { 
     'use strict'; 
     var i, len; 
     for (i = 0, len = this.length; i < len; ++i) { 
      if (i in this) { 
       fn.call(scope, this[i], i, this); 
      } 
     } 
    }; 
} 

运行例如here

+0

不错!它完美的作品! 我会看到这段代码来理解它。非常感谢 ! –

1

你的算法是错误的。切分数组后,您正在推送索引。您可以直接发送该项目,或者在切片之前进行推送。

加上你可以发送项目作为参数从你的HTML角功能。

<a href='' ng-click='goToLastList(item, $index)'>{{item.pos}} - {{item.text}}</a> 


    $scope.goToLastList = function (item, idx) { 
     var dptToMoveList2 = $scope.dpt[idx]; 
     console.log(dptToMoveList2); 
     $scope.dpt.splice(idx,1); 
     console.log('idx : '+idx); 
     $scope.dptRecep.push(item); 
    } 

小提琴:http://jsfiddle.net/RmFYv/2/

+0

仍有错误.. –

+0

如果您点击他们消失的列表右侧的元素! –

+0

这是因为你必须对右侧的元素做同样的事情。这只是左侧的代码片段。 – erdimeola

0

你也尝试插入后排序:

$scope.goToLastList = function (item, pos, idx) { 
    var dptToMoveList2 = $scope.dpt[idx]; 
    console.log(dptToMoveList2); 
    $scope.dpt.splice(idx,1); 
    console.log('idx : '+idx); 
    $scope.dptRecep.push({ 
     text: dptToMoveList2.text, 
     pos: dptToMoveList2.pos 
    }); 
    $scope.dptRecep.sort(function (a,b) { return a.pos - b.pos }) 

http://jsfiddle.net/wV3eY/