我正在努力解决问题,并希望得到您的建议。 我已经设置了一个向上或向下移动某些块的代码
问题是,我正在尝试移动的块是位置-1。所以大家在第一次点击时工作正常。但是当我再次尝试移动它时,不是从新获得的位置完成工作,而是再次使用-1。因为我移动的第一个现在是0,它将永远不会完成工作,具体取决于已移动的块。 有人可以帮帮我吗?这有点让我发疯。
$scope.move = (origin, destination, item, position, new_position, is_a_theme) ->
console.log($scope)
console.log($scope.item)
temp = $scope.$ctrl.themes[destination]
$scope.$ctrl.themes[destination] = $scope.$ctrl.themes[origin]
$scope.$ctrl.themes[origin] = temp
$scope.moveUp = (position) ->
if $scope.item.active = true & is_a_theme = true
$scope.move($scope.item.position - 1, $scope.item.position - 2)
$scope.moveDown = (position) ->
if $scope.item.active = true & is_a_theme = true
$scope.move($scope.item.position - 1, $scope.item.position)
答案 0 :(得分:0)
在尝试时我发现使用findIndex
更直接。
示例代码:
angular.module('test', []).controller('Test', TestController);
function TestController($scope) {
$scope.items = [
{name: 'A'},
{name: 'B'},
{name: 'C'},
{name: 'D'}
]
$scope.select = function(item) {
$scope.items.forEach(function(i) {
i.active = (i == item);
});
}
$scope.up = function() {
var selectedIndex = $scope.items.findIndex(function(i) {
return i.active;
});
swap(selectedIndex, selectedIndex - 1);
}
$scope.down = function() {
var selectedIndex = $scope.items.findIndex(function(i) {
return i.active;
});
swap(selectedIndex, selectedIndex + 1);
}
function swap(a, b) {
if (a < 0 || b < 0 || a >= $scope.items.length || b >= $scope.items.length) {
return;
}
var tmp = $scope.items[a];
$scope.items[a] = $scope.items[b];
$scope.items[b] = tmp;
}
}
.item {
width: 100px;
height: 25px;
margin-bottom: 5px;
border: 1px solid black;
}
.item.active {
background-color: yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<div ng-app='test' ng-controller='Test'>
<div class='item'
ng-repeat='item in items'
ng-class='{active: item.active}'
ng-click='select(item)'>
{{item.name}}
</div>
<br>
<br>
<button type='button' ng-click='up()'>up</button>
<button type='button' ng-click='down()'>down</button>
</div>