在ng重复使用隐藏元素完成后执行函数

execute function after ng-repeat finishes with hidden elements

本文关键字:执行 函数 元素 隐藏 ng      更新时间:2023-09-26

这是情况,我有这个代码

<div data-ng-repeat="question in questions" data-ng-if="cQuestion == $index + 1" class="question-animate">
  {{question.question}}-{{$index + 1}}
  <div data-ng-repeat="answerswer in question.answers">
    {{answer}}&nbsp
  </div>
  <input type="button" value="next" data-ng-click="nextQuestion()"/>
</div>

我想检测ng重复何时完成,这样我就可以更新cQuestion来显示第一个问题。由于我们有data-ng-if="cQuestion == $index + 1",它一开始计算为false,并且元素没有显示,这限制了我检测ng repeat何时完成的选项。我尝试过一个指令,但由于元素没有显示,指令也没有被激发。ng if之所以存在,是因为存在挂接到重复对象的动画。现在我用setTimeout来完成,但我认为这种技术不可靠。

让我们将索引cQuestion移出视图。

你的控制器应该完成这项工作。创建一个变量currentQuestion,表示当前显示的问题。

<div>
  {{currentQuestion.question}}-{{currentQuestionIndex+1}}
  <div data-ng-repeat="answerswer in currentQuestion.answers">
    {{answer}}&nbsp
  </div>
  <input type="button" value="next" data-ng-click="nextQuestion()"/>
</div>

然后确保nextQuestion确实改变了当前的问题:

function nextQuestion(){
    $scope.currentQuestion = $scope.questions[$scope.currentQuestionIndex];
    $scope.currentQuestionIndex ++; //init with 0
}

不要忘记在控制器开始时用第一个问题初始化$scope.currentQuestion