多个$ http.get operatios并将信息保存在一个$ scope变量中

时间:2018-05-17 02:07:24

标签: javascript html scope angularjs-scope

我需要做四个$ http.get调用,我需要将返回的$ scope变量发送到一个HTML来打印所有信息。目前我在JS中有下一个代码:

(function (ng) {

var mod = ng.module("serviciosAdminModule");

mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/hoteles").then(function (response) {
            $scope.serviciosHotelesRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/paseos").then(function (response) {
            $scope.serviciosPaseosRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/aseos").then(function (response) {
            $scope.serviciosAseosRecords = response.data;
        });
    }]);
mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $http.get("api/entrenamientos").then(function (response) {
            $scope.serviciosEntrenamientosRecords = response.data;
        });
    }]);

})(window.angular);

在HTML中我有下一个:

<tr ng-repeat="servicio in serviciosAdminRecords">
    <td id="{{$index}}-id" class="parrafoscards" style="font-size: 16px">
        <a ui-sref="servicioAdminDetail({servicioId: servicio.id})">{{servicio.id}}</a>
    </td>...

在HTML中我要求serviciosAdminRecords,它是$ scope变量,我想放置所有.get数据

2 个答案:

答案 0 :(得分:0)

您可能需要链接承诺,以便将所有响应一起添加到一个数组中。摆脱所有不同的控制器 - 它们将具有单独的范围 - 并且只有一个控制器,通过在视图中使用ng-controller='serviciosAdminCtrl'作为属性,确保在视图中使用它。

mod.controller('serviciosAdminCtrl', ['$scope', '$http',
    function ($scope, $http) {
        $scope.serviciosAseosRecords = [];
        $http.get("api/hoteles").then(function (response) {
            $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
            $http.get("api/paseos").then(function (response) {
                $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                $http.get("api/aseos").then(function (response) {
                    $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                    $http.get("api/entrenamientos").then(function (response) {
                        $scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data);
                    });
                });
            });
        });
    }]);

答案 1 :(得分:0)

如果您的response.data是一个对象数组,则将serviciosPaseosRecords初始化为数组。

$scope.serviciosHotelesRecords = [];

而不是将response.data分配给serviciosPaseosRecords

 $scope.serviciosAseosRecords = response.data

Concat response.data与现有的serviciosAseosRecords数组。

$scope.serviciosAseosRecords = $scope.serviciosAseosRecords.concat(response.data)