尝试连接Angular.js或JavaScript中的两个函数返回

Trying to join two function returns in Angular.js or JavaScript

本文关键字:两个 返回 函数 连接 Angular js JavaScript      更新时间:2023-09-26

我有下面的Angular控制器。我想从xy变量中提取项目,并在网页上显示它们。目前,网页仅显示y变量中的项目。我尝试使用.push()将两个函数结果集放在PremByClass数组中。如能提供任何帮助或指导,我们将不胜感激。

app.controller('PremByClass', ['$scope', '$http', 'policyApi', 'lookupApi', function ($scope, $http, policyApi, lookupApi) {
    $scope.model = {};
    $scope.load.then(function () {
        function formatDate(value) {
            return value.getMonth() + 1 + "-" + value.getDate() + "-" + value.getFullYear();
        }
        $scope.PremByClass = [];
        policyApi.policy.get().then(function (t) {
            if (t) {
                policyApi.class.get().then(function (x) {
                    if (x) {
                        //Put x into $scope.PremByClass
                        $scope.PremByClass.push(x);
                        var dtEff = formatDate(t.DateEffective);
                        for (var i = 0, e = null; e = x[i]; i++) {
                            lookupApi.WCClassDesc.get(e.GovState, e.classCode, e.DescCode, dtEff).then(function (y) {
                                //This seems to wrok correctly however it seems that $scope.PremByClass forgets about x
                                //The web page only shows stuff from y
                                $scope.PremByClass.push(y);
                            })
                        }
                    }
                })
            }
        })
    });
}]);

因为您的x变量似乎是一个数组,我想您应该在页面中将其显示为对象列表或表,其中包含以下内容:

<ul>
  <li ng-repeat="item in PremByClass[0]">
    {{item.GovState}} // {{item.classCode}}
  </li>
</ul>

我在PremByClass上使用了索引0,因为您的x变量是您推入PremByClass数组的第一个项。尽管如此,通过将x变量设置为更有意义的scope属性,我会使代码的这一部分更易于维护。

您可以替换控制器中的这条线路:

$scope.PremByClass.push(x);

这行:

$scope.policies = x;

然后简单地重写ng重复块以使用策略:

<ul>
  <li ng-repeat="item in policies">
    {{item.GovState}} // {{item.classCode}}
  </li>
</ul>

变量/数组PremByClass将只包含lookupApi.WCClassDesc服务或工厂的结果,并且您应该能够使用与上述相同的ng重复代码在屏幕上呈现它们,只需将策略替换为PremByClass即可。