我正在努力解决一个问题,请得到您的建议。 我已经设置了一个向上或向下移动一些块的代码
问题是,我试图移动的块是一个位置 -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)
在尝试时,我发现使用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>