javascript - 来自模板 ng-repeat 的 AngularJS 子 $http.post

标签 javascript angularjs

在我的 AngularJS 应用程序中,我通过 Controller 上的 $http.post(我使用的是 json rpc API)获取数据,然后我使用

呈现该数据(项目数组)
<div ng-repeat="item in arrayItems">
    {{ makeANewHttpRequest(item.relatedItemId).propertyName }}
</div>

我需要的是实现 $scope.makeANewHttpRequest(itemId) 函数,它的调用次数与 arrayItems.length 一样多,并从新的 $http.post 请求中返回 relatedItem 对象。

我该怎么做? 这是一个好的做法吗?

最佳答案

首先你需要创建一个工厂来负责调用已经暴露给其他人的$http.post,它会返回promise对象。您可以通过添加 dataService 工厂作为对 Controller 依赖项的引用来调用该服务方法。 Controller 将调用服务函数,如 dataService.getData(url, data) & 在每个 promise 解决时,它将增加计数器,更新数据,然后调用下一个 post 如果 arrayItems计数不超过计数器。

工厂

var myModule = angular.module('myModule', []);
myModule.factory('dataService', function($http) {
    var getData = function(url, data) {
        return $http.post(url, {
            data
        }).then(function(res) {
            return res.data;
        });
    };

    return {
        getData: getData
    }
});

Controller

myModule.controller('mainCtrl', function($scope, dataService) {
    //other code
    $scope.counter = 0;
    $scope.makeANewHttpRequest = function(id) {
        dataService.getData(url+id, data).then(function(data) {
            $scope.data = data; //updated the data each time when response received
            ++$scope.counter; //increment counter
            if ($scope.counter >= $scope.arrayItems.length) //check counter should not exceed limit
                $scope.makeANewHttpRequest(id);
        });
    }
});

HTML

ng-click="counter=0;$scope.makeANewHttpRequest(id)" //clear count and call method

希望对您有所帮助,谢谢。

关于javascript - 来自模板 ng-repeat 的 AngularJS 子 $http.post,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28887104/

相关文章:

javascript - 如何测试 Javascript 对象在最后一个嵌套级别是否只有空对象?

javascript - 尽管存在 <img> 标签,但图像未显示且没有错误

javascript - Webstorm - Typescript、AngularJS 和生成器 ng-poly Getter/Setter

javascript - 如何有条件地应用 Angular 状态提供者

angularjs - ionic 页面显示没有标题

javascript - 在AngularJS中使用routeParams创建templateUrl

javascript - 合并两个 JavaScript 对象

javascript - 如何在node.js中获取window.location.hash中的变量

javascript - WinJS - 如何访问 LED 闪光灯(在 Windows Phone 上)?

CKEditor 中的 JavaScript