cheked複選框返回值的時候選中
阿新 • • 發佈:2019-06-09
html
<div ng-repeat="item in businessType">
<input type="checkbox" ng-class="{namecheck: item.name=='null'}" ng-model="item.checked" ng-change="selectOne()">
</div>
js
1.單選選中的時候 $scope.checkedList = [] $scope.selectOne = function () { console.log($scope.businessType) angular.forEach($scope.businessType , function (i) { console.log(i.checked) var index = $scope.checkedList.indexOf(i.code); if(i.checked && index === -1) { $scope.checkedList.push(i.code); } else if (!i.checked && index !== -1){ $scope.checkedList.splice(index, 1); }; }) console.log($scope.checkedList); } 2.ajax返回資料的時候 for(let i = 0;i < data.data[0].businessTypes.length;i++){//這一層迴圈是介面返回的資料 $scope.checkedList.push(data.data[0].businessTypes[i].code)//如果有code的時候就把code壓入陣列中 for(let k = 0;k < $scope.businessType.length;k++){//這一層迴圈是原始資料 if($scope.businessType[k].code === data.data[0].businessTypes[i].code){//讓原始資料與返回資料的code做對比如果相等就是選中的狀態 $scope.businessType[k].checked = true; break; } } }
總結
剛開始做的時候我是用原始資料做外層迴圈的結果只有選中陣列的最後一個是選中的狀態,後來找到原因是因為外層迴圈的資料比內層迴圈的資料多,如果選中的只有2個,外層迴圈5個,外層迴圈能迴圈5次內層迴圈只能迴圈2次,所以多的3個還會和他做對比又會重新賦值。因此需要返回的資料放在外層和原始資料做對比,他有2個迴圈2此和原始資料一次做對比,所以這樣就好啦
每一次遇到的bug都要用心去做總結避免