当ng-repeat / ng-class调用一个调用$ http的函数时,无限循环

时间:2015-12-23 17:31:47

标签: javascript angularjs

如果你不知道这是什么,请阅读:Infinite loop with Angular expression binding

在html文件中:

<ui ng-repeat="carrierDetail in carrierDetails">
    <li>
        <i ng-class="{'icon-sign-blank':getStatus(carrierDetail.carrierId)==0,'icon-green':getStatus(carrierDetail.carrierId)==1,'icon-orange':getStatus(carrierDetail.carrierId)==2,'icon-red':getStatus(carrierDetail.carrierId)==3}"></i>
        <ul ng-repeat="owner in getOwners(carrierDetail.carrierId)">
            <li>{{owner.ownerName}}</li>
        </ul>
    </li>
</ui>

如您所见,getStatus()中调用了函数ng-classgetOwners()中调用了另一个函数ng-repeat。并且,这两个函数都将调用$http service:

$scope.getOwners = function(carrierId) {
    $http.get($scope.baseurl.smart,carrierId,1).then(function(data) {
        return data.data.carrierOwners; // Returns an aray
    }, function(data) {
        return [];
    });
}

$scope.getStatus = function(carrierId) {
    $http.get($scope.baseurl.smart,carrierId,1).then(function(data) {
        return [1, 2, 3].indexOf(data.data.carrierStatus) != -1 ? data.data.carrierStatus : 0; // Returns an integer
    }), function(data) {
        return 0;
    };
}

所以,我已经知道这两个函数都有无限的调用。但我无法想出一个解决方案。也许我可以为任何一个函数创建一个指令。但我不知道如何在ng-classng-repeat中使用该指令。有没有更简单的方法?感谢。

1 个答案:

答案 0 :(得分:0)

首先,你的html不应该非常强烈地调用函数 (点击之类的东西除外。

<ui ng-repeat="carrierDetail in carrierDetails">
    <li>
        <i ng-class="{'icon-sign-blank':carrierDetail.carrierId==0,'icon-green':carrierDetail.carrierId==1,'icon-orange':carrierDetail.carrierId==2,'icon-red':carrierDetail.carrierId==3}"></i>
        <ul ng-repeat="owner in owners">
            <li>{{owner.ownerName}}</li>
        </ul>
    </li>
</ui>

JS,一般的想法是:

// assuming controller defined:
$scope.carriers = some kind of array;

$scope.getOwners = function(carrierId) {
    $http.get($scope.baseurl.smart,carrierId,1).then(function(data) {
        return data.data.carrierOwners; // Returns an arary
    }, function(data) {
        return [];
    });
}

$scope.getStatus = function(carrierId) {
    $http.get($scope.baseurl.smart,carrierId,1).then(function(data) {
        return [1, 2, 3].indexOf(data.data.carrierStatus) != -1 ? data.data.carrierStatus : 0; // Returns an integer
    }), function(data) {
        return 0;
    };
}



for( var i in $scope.carriers){

    $scope.getOwners( $scope.carriers[ i ].carrierId ).then(function(success){
        // add data to array
    });

}