在ng-repeat完成隐藏元素后执行函数

时间:2014-04-23 08:36:53

标签: javascript angularjs angularjs-ng-repeat

这是情况,我有这个代码

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

我想检测ng-repeat完成的时间,以便我可以更新cQuestion以显示第一个问题。由于我们首先将data-ng-if="cQuestion == $index + 1"计算为false,并且未显示该元素,因此这限制了检测ng-repeat完成时的选项。我已尝试使用指令,但由于元素未显示且指令未被触发。 ng-if是因为有重复对象挂钩的动画。 现在我正在使用setTimeout,但我认为这种技术不可靠。

1 个答案:

答案 0 :(得分:0)

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

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

<div>
  {{currentQuestion.question}}-{{currentQuestionIndex+1}}
  <div data-ng-repeat="answer 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

相关问题