在AngularJS中使用拖放功能时,当在ng-repeat中使用动态索引时,可能会出现问题。以下是一个解决这个问题的示例代码:
HTML代码:
-
{{ item.name }}
drop here
JavaScript代码:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
$scope.items = [
{ name: 'Item 1' },
{ name: 'Item 2' },
{ name: 'Item 3' }
];
$scope.dragStart = function(index) {
$scope.dragIndex = index;
};
$scope.drop = function(index) {
var item = $scope.items[$scope.dragIndex];
$scope.items.splice($scope.dragIndex, 1);
$scope.items.splice(index, 0, item);
};
});
在这个示例中,ng-repeat指令用于循环遍历items数组,并为每个元素创建一个可拖放的li项。拖动开始时,dragStart函数会将当前元素的索引保存到$scope.dragIndex变量中。当拖动元素放置到droppable区域时,drop函数会根据保存的索引对items数组进行重新排序。
通过这种方式,可以在ng-repeat中使用动态索引来实现拖放功能。