遇到一个bug,代码如下
<label>选项:</label>
<div ng-repeat="item in questions[currentIndex].options" ng-init="innerIndex = $index">
<span>选项内容:</span>
<textarea class="form-control" rows="5" ng-disabled="item.isCustOmized" ng-model="item.content"></textarea>
<span>选择此选项是否让被调查者继续回答下一题:</span>
<input class="unchecked" ng-class='{"checked": item.isNext}' type="checkbox" ng-model="item.isNext" />
<br/>
<span>此选项是否由被调查者自行输入:</span>
<input class="unchecked" ng-class='{"checked": item.isCustOmized}' type="checkbox" ng-model="item.isCustOmized" />
<br/>
<div ng-if="questions[currentIndex].isSetSkip">
<span>是否跳题至Group1:</span>
<input class="unchecked" ng-class='{"checked": item.isSkipOne}' type="checkbox" ng-model="item.isSkipOne" ng-click="switchSkipIndex($event, item, questions[currentIndex].group)" />
</div>
<div style="text-align:right;margin-top: -20px;">
<button class="btn btn-danger btn-xs" ng-click="deleteOption(questions[currentIndex].options, innerIndex)">删除该选项</button>
</div>
<br/><br/><br/>
</div>
<button class="btn btn-success btn-xs" style="margin-right:30px;" ng-click="addOption()">继续添加选项</button>
<div style="text-align:right;margin-top: -20px;">
<button class="btn btn-danger btn-xs" style="margin-right:30px;" ng-click="deleteQuestion()">删除问题</button>
<button ng-show="currentIndex > 0" class="btn btn-info btn-xs" style="margin-left:4%;" ng-click="lastQues()">上一题</button>
<button class="btn btn-info btn-xs" style="margin-right:4%;margin-left: 4%;" ng-click="nextQues()">下一题</button>
<button class="btn btn-primary btn-xs" ng-click="finishCreate()" ng-disabled="isSubmit">完成创建</button>
</div>
$scope.deleteOption = function(options, index) {
if (options.length == 0 || options.length == 1 && index == 0) {
$scope.tip = "问题选项不得为空!";
tipWork();
return;
}
options.splice(index, 1);
console.log(index)
console.log(options)
}
发现删除options数组后,innerIndex的值一直保持最初的值,而数组明明改变了,页面也重新渲染了,仔细看了以下代码发现了ng-init,想到它只在初始化时执行一次,options改变并没有引起它的执行,把ng-init去掉就行了.
至于我为什么要用ng-init保存索引值是为了多层ng-repeat时$index只能保存一个被遍历的数组的索引.