-1

我需要添加元素,我以 JSON 格式将其作为 $scope.array 添加到数组中 我的代码是:

$scope.sections=function(){
    $scope.array=[];

    $http.get("/app/query/?mod=find&type=all").success(function(data){

        $.each(data, function(i, row){
            $scope.array.push('aaa');
            console.log(row);
        });


    });
    return $scope.array;
}
console.log($scope.sections());

但是这个函数返回空数组,我怎样才能添加元素$scope.array

此字符串将数据正确添加到控制台console.log(row);,但$scope.array.push不起作用

4

2 回答 2

3

As $http is async it will return a empty array, because it takes time to get the data from the server, that's why console.log(row) returns the data correctly.

Also you need to call $scope.$apply() in order to apply the new data to the scope.

 $scope.sections=function(callback){
  $scope.array=[];

  $http.get("/app/query/?mod=find&type=all").success(function(data){
       var temp = [];
       $.each(data, function(i, row){
          temp.push('aaa');
          console.log(row);
       });

       $scope.$apply(function () {
          $scope.array = temp;
       });        

       callback($scope.array);
   });
 }

 $scope.sections(function(result) { console.log(result); });
于 2013-10-18T14:33:28.443 回答
2

我实际上会将它修改为更像这样的东西

$scope.sections=function(){
  return $http.get("/app/query/?mod=find&type=all").then(function(resp){
      var array = [];
      angular.forEach(resp.data, function(row, i){
          array.push(row);
          console.log(row);
      });
      return array;
  });
};
$scope.array = $scope.sections();
$scope.array.then(function(data) { console.log(data); });

在这种情况下,我们只需从函数中返回整个 Promise。现在 $scope.array 是一个承诺,而不是一个原始值。

在返回 promise 之前,我们执行了一个额外的 then 函数来操作返回值。我们希望将它转换为一个数组,以便未来的 Promise 用户将看到它解析为数组而不是对象。您可以在此处进行所需的任何转换,我只是从您的问题中获取逻辑。

请记住,现在您的代码必须知道如何处理一个承诺,而不是一个数组,但是这样您可以确保始终解析该值。如果您确实需要将其绑定到 UI,使用插值或其他方式,Angular 将自动解析 Promise。例如

<div>{{array}}</div>

在您的标记中将自动解析为准备就绪时创建的数组。不需要额外的代码。

于 2013-10-18T14:38:21.807 回答