角度调用http请求到函数ng-repeat返回

时间:2016-01-04 15:10:01

标签: javascript angularjs http

我想在mg-repeat中调用一个函数,这个函数调用带有id的http请求来查找列表数据,但是当我尝试这个时,我有一条错误消息。

这是一个功能调用:

<div ng-repeat="ListeReponse in reponsefonction(Listechamps.keyQuestion)" >
    <label class="col-xs-4 control-label">
        {{ListeReponse.reponse}}
    </label>
</div>

这是一个功能:

$scope.reponsefonction  = function(idQuestion)
{
    var defer = $q.defer();
    return RequestService.get('question/'+idQuestion+'/reponse').success(function(data) 
    { 
        defer.resolve(data);
    })
    return defer.promise;
}

我的服务:

app.factory('RequestService', function ($http, WEB_SERVICE_URL) 
{
    var requestService = {};
    requestService.get = function (type) 
    {
        var response = $http.get(WEB_SERVICE_URL.url+type);
        return response;
    };

    // ajout
    requestService.post = function (type, data) 
    {
        var response = $http.post(WEB_SERVICE_URL.url+type, data);
        return response;
    };

    requestService.put = function (type, data) 
    {
        var response = $http.put(WEB_SERVICE_URL.url+type, data);
        return response;
    };

    return requestService;
})

错误消息:

  

docs.angularjs.org/error/$rootScope/infdig?p0=10&p1=%5B%5D

2 个答案:

答案 0 :(得分:0)

您创建了一个infitie循环。每次通话都会触发另一个通话。每次调用返回时,Angular都会评估responseFunction。您需要稍微重新处理您的应用程序:

不要在ng-repeat中调用函数。而是简单地将它链接到变量。使用get查询在启动时填充变量一次。

答案 1 :(得分:0)

我不认为ng-repeat适用于承诺。在这种情况下,ng-repeat循环遍历“null / undefined”,这会导致此错误。

试试这个:

HTML:

<div ng-repeat="ListeReponse in getResponses(Listechamps.keyQuestion)" >
    <label class="col-xs-4 control-label">{{ListeReponse.reponse}}</label></div>

控制器:

var idQuestions = {}; // keep track of the entire list
$scope.getResponses = function(idQuestion) {
  var notInitialized = idQuestions[idQuestion] == null;
  idQuestions[idQuestion] = notInitialized ? [] : idQuestions[idQuestion]; // initialize to empty array
  if (notInitialized) {
    $scope.reponsefonction(idQuestion); //kicks off ajax request to get data
  }
  return idQuestions[idQuestion];
}

$scope.reponsefonction = function(idQuestion) {
  RequestService.get('question/' + idQuestion + '/reponse').success(function(data) {
      //assuming data is an []
      Array.prototype.push.apply(idQuestions[idQuestion], data); //update the same array object to prevent multiple $digest cycles

    }
  }
}