Angularjs 为什么我的控制器函数被调用了这么多次?

Angularjs 为什么我的控制器函数被调用了这么多次?,angularjs,Angularjs,我的控制器具有以下功能: $scope.isStageCompleted = function (stage) { return stage.StageId < $scope.currentStage.StageId ? "complete" : "pending"; }; $scope.isStageCompleted=函数(阶段){ return stage.StageId

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

    $scope.isStageCompleted = function (stage) {
        return stage.StageId < $scope.currentStage.StageId ? "complete" : "pending";
    };
$scope.isStageCompleted=函数(阶段){
return stage.StageId<$scope.currentStage.StageId?“完成”:“待定”;
};
在我看来,有两个地方叫做:

        <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>

  • {{{stage.StageName}}{{isStageCompleted(stage)}

  • 因为它在两个地方使用,并且在阶段列表中有10个阶段,我希望它被调用20次。但是它被调用了200次,我不知道为什么。

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

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

    因为任何摘要循环都会触发
    isStageCompleted()
    ,所以有没有更有效的方法来执行此操作,或者这是否正确?能否将其添加到
    stage
    对象中?一次性绑定看起来很酷。但是如果我使用其他解决方案并将结果保存到stage对象,我猜我必须在控制器加载中调用isStageCompleted,因为它不再从视图中调用了,对吗?没错。我还在我的答案中添加了另一个更改,使用
    ngInit
    来减少拨打电话的次数controller@Legion添加了我的最终解决方案,即完全不使用函数,只是一个纯angularJS表达式解决方案
    <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>
    
    <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>