问题描述:
今天老大让改项目中的bug,我发现ng-repeat循环输出时,利用ng-if显示数据结果总是一致的,后台输出完全没有问题,显示的结果与后台打印的不一致,看了半天才发现是$scope的问题
![](https://img.haomeiwen.com/i6765544/3eb7d33004f8f392.png)
1-1、修改前html页面代码(局部):
<li ng-repeat="item in data">
名称:<h3>{{item.Name}}</h3>
<div ng-if="isAttendNeed">
<button type="button" class="btn btn-info"><span style="font-size:larger;">报 名</span></button>
</div>
<div ng-if="isAttendAll">
<button type="button" class="btn btn-default"><span style="font-size:larger;">已报名</span></button>
</div>
<div ng-if="isUnAttendAll">
<button type="button" class="btn btn-default"><span style="font-size:larger;">已 满</span></button>
</div>
<li ng-repeat="item in data">
1-2、修改前部分js代码:
if (response) {
console.log(item);
$scope.isDisabled = true;
$scope.isAttendAll = true;//已报名
$scope.isAttendNeed = false;
$scope.isUnAttendAll = false;
}else {
if ($scope.IsFullTrain) {
$scope.isUnAttendAll = true;//未参加,人数已满(已满)
$scope.isAttendNeed = false;
$scope.isAttendAll = false;
} else {
$scope.isAttendNeed = true;//报名
$scope.isAttendAll = false;
$scope.isUnAttendAll = false;
}
}
console.log($scope.isAttendNeed + "报名");
console.log($scope.isAttendAll + "已报名");
console.log($scope.isUnAttendAll + "已满");
说明:
$scope是全局变量,所以循环输出数据时,$scope.isAttendNeed、$scope.isAttendAll、$scope.isUnAttendAll三个属性的值等于最后一次所赋的值,所以循环出所有数据显示的结果是一致的。
解决方法:
将这三个属性设置成局部变量即可,将$scope换成item,在html页面中利用item.属性即可正常显示。
![](https://img.haomeiwen.com/i6765544/98c129415b33d5d7.png)
2-1、修改后html页面代码(局部):
<li ng-repeat="item in data">
名称:<h3>{{item.Name}}</h3>
<div ng-if="item.isAttendNeed">
<button type="button" class="btn btn-info"><span style="font-size:larger;">报 名</span></button>
</div>
<div ng-if="item.isAttendAll">
<button type="button" class="btn btn-default"><span style="font-size:larger;">已报名</span></button>
</div>
<div ng-if="item.isUnAttendAll">
<button type="button" class="btn btn-default"><span style="font-size:larger;">已 满</span></button>
</div>
<li ng-repeat="item in data">
2-2、修改后部分js代码:
if (response) {
console.log(item);
item.isDisabled = true;
item.isAttendAll = true;//已报名
item.isAttendNeed = false;
item.isUnAttendAll = false;
}else {
if (item.IsFullTrain) {
item.isUnAttendAll = true;//未参加,人数已满(已满)
item.isAttendNeed = false;
item.isAttendAll = false;
} else {
item.isAttendNeed = true;//报名
item.isAttendAll = false;
item.isUnAttendAll = false;
}
}
console.log(item.isAttendNeed + "报名");
console.log(item.isAttendAll + "已报名");
console.log(item.isUnAttendAll + "已满");
网友评论