在 ng-repeat 中使用 http 功能会使网站崩溃

using http function in ng-repeat crashes website

我正在使用 ng-repeat 循环遍历我的数据。在我的 ngrepeat 中,我启动了一个函数来获取 2 个邮政编码之间的邮政编码距离,它看起来像这样

    <a href="#" class="list-group-item" style="overflow:auto;" ng-repeat="(key, delcomp) in openDeliveryoptions" ng-show="showCategory(delcomp.catid)">
        <span ng-show="delcomp.delivery_multiple_locations == 'No' && delcomp.delivery_zip != ''">{{getDistance(delcomp.delivery_zip,searchedZip4pp)}}</span>
    </a>

然后在控制器中

//get distance
$scope.getDistance = function(zipDelcomp,zipSearched) {
zipDelcomp = zipDelcomp.replace(/\s/g, '');
zipDelcomp = zipDelcomp.slice(0,4);

//Get request
$http({
    url: url+"/getdistance?zip1=" + zipDelcomp + "&zip2=" + zipSearched,
    method: 'GET',
    headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function(data){
    console.log(data)
}).error(function(err){"ERR", console.log(err)});

}

但是当我这样做时..我的浏览器崩溃然后每秒显示此错误直到崩溃

 Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []
http://errors.angularjs.org/1.3.12/$rootScope/infdig?p0=10&p1=%5B%5D
    at angular.js:63
    at Scope.$digest (angular.js:14281)
    at Scope.$apply (angular.js:14506)
    at done (angular.js:9659)
    at completeRequest (angular.js:9849)
    at XMLHttpRequest.requestLoaded (angular.js:9790)
angular.js:63 Uncaught Error: [$rootScope:infdig] 10 $digest() iterations reached. Aborting!
Watchers fired in the last 5 iterations: []

更好的方法是在控制器中的 ngRepeat 之外执行请求,并将值保存在变量中。

这方面的东西(未测试,可以优化):

    <div ng-controller="MyCtrl">
        <a href="#" class="list-group-item" style="overflow:auto;" ng-repeat="(key, delcomp) in openDeliveryoptions" ng-show="showCategory(delcomp.catid)">
            <span ng-show="delcomp.delivery_multiple_locations == 'No' && delcomp.delivery_zip != ''">{{distances[delcomp.delivery_zip]}}</span>
        </a>
    </div>

    angular.module(...).controller(..., function ($scope, $q) {
        $scope.searchedZip4pp = "1234"
        $scope.openDeliveryoptions = {...};
        var distances = {};
        var promises = [];

        angular.forEach($scope.openDeliveryoptions, function (openDeliveryoption) {
            var zipDelcomp  = openDeliveryoption.delivery_zip.replace(/\s/g, '').slice(0,4);

            if (zipDelcomp in distances) {
                return ;
            }

            distances[zipDelcomp] = "";

            promises.push($http.get(url+"/getdistance", { zip1: zipDelcomp, zip2: zipSearched })
            .success(function(data){
                distances[zipDelcomp] = data.value;
            }));
        });

        $q.all(promises)
        .then(function() {
            $scope.distances = distances;
        });
    });