为什么我的控制器功能被调用了这么多次?

时间:2016-03-24 17:41:23

标签: angularjs

我的控制器中有以下功能:

    $scope.isStageCompleted = function (stage) {
        return stage.StageId < $scope.currentStage.StageId ? "complete" : "pending";
    };

在我看来,它在两个地方被召唤:

        <ol>
            <li ng-repeat="stage in stageList" id="progressStage{{ stage.StageId }}" class="{{ isStageCompleted(stage) }}">{{ stage.StageName }}<span class="sr-only"> {{ isStageCompleted(stage) }}</span></li>
        </ol>

由于它在两个地方使用,并且在舞台列表中有10个阶段,我希望它被称为20次。但它被称为200次,我无法弄清楚原因。

1 个答案:

答案 0 :(得分:1)

将函数的结果保存到stage对象:

$scope.isStageCompleted = function (stage) {
    stage.status = stage.StageId < $scope.currentStage.StageId ? "complete" : "pending";
};

并且在观点上:

<li ng-repeat="stage in stageList" id="progressStage{{ stage.StageId }}" class="{{ stage.status }}">{{ stage.StageName }}<span class="sr-only"> {{ stage.status }}</span></li>

如果您不需要更新输出,也可以使用一次性绑定:

<li ng-repeat="stage in stageList" ng-init="isStageCompleted(stage)" id="progressStage{{ stage.StageId }}" class="{{ ::stage.status }}">{{ stage.StageName }}<span class="sr-only"> {{ ::stage.status }}</span></li>

在表达式make之前添加::以在下一个摘要循环中忽略它(在表达式输出呈现到文档中之后)

最后编辑:

<li ng-repeat="stage in stageList" id="progressStage{{ stage.StageId }}" ng-class="{'pending': stage.StageId >= currentStage.StageId, 'complete': stage.StageId < currentStage.StageId}">{{ stage.StageName }}<span class="sr-only"> {{ stage.StageId < currentStage.StageId ? "complete" : "pending" }}</span></li>