最近有一个拖拽排序的功能遍历后无法直接读取index 和 item。换了一种思路实现功能
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body ng-controller="demoController">
<ul class="list">
<li draggable="true" ng-repeat="li in arr track by $index" data-value="{{li.value}}" data-id="{{li.id}}">{{li.value}}{{$index}}</li>
</ul>
<button ng-click="save()">保存数据</button>
<script src="https://cdn.bootcdn.net/ajax/libs/angular.js/1.8.3/angular.min.js"></script>
<script src="/bundle.js"></script>
</body>
</html>
let app = angular.module('myApp', []);
app.controller('demoController', ['$scope', function($scope) {
$scope.arr = [{
value: '赵',
id: 1
}, {
value: '钱',
id: 2
}, {
value: '孙',
id: 3
}, {
value: '李',
id: 4
}, {
value: '周',
id: 5
}];
let list = document.querySelector('.list')
let currentLi;
list.addEventListener('dragstart', (e) => {
e.dataTransfer.effectAllowed = 'move'
currentLi = e.target
setTimeout(() => {
currentLi.classList.add('moving')
})
})
list.addEventListener('dragenter', (e) => {
e.preventDefault()
if (e.target === currentLi || e.target === list) {
return
}
let liArray = Array.from(list.childNodes)
let currentIndex = liArray.indexOf(currentLi)
let targetindex = liArray.indexOf(e.target)
if (currentIndex < targetindex) {
list.insertBefore(currentLi, e.target.nextElementSibling)
} else {
list.insertBefore(currentLi, e.target)
}
})
list.addEventListener('dragover', (e) => {
e.preventDefault()
})
list.addEventListener('dragend', (e) => {
currentLi.classList.remove('moving')
//操作完毕赋值
for (let k = 0; k < list.children.length; k++) {
$scope.arr[k] = {
value: list.children[k].dataset.value,
id: list.children[k].dataset.id
};
}
})
$scope.save = function() {
console.log($scope.arr)
}
}]);
标签:方案,list,value,id,let,angularjs,scope,currentLi,拖拽 From: https://www.cnblogs.com/yiyangl/p/17359807.html