如何从同一控制器中的其他方法访问$ scope异步数据

时间:2019-06-05 11:45:04

标签: angularjs angular-promise

当我的作用域有两个属性,每个属性包含一个从数据库异步检索的数组时,我不能优雅地访问另一个属性。我确定我一定会错过一些东西,因为我当前的解决方案感觉像是黑客。

我有一个Angular CRUD页面,其中包含一个表和一个包含下拉选择控件的表单。当我单击表中的一行并要对其进行更新时,我需要使用当前值填充下拉列表。为了正确处理此问题,我目前正在声明一个全局变量,并在从数据库中检索到该变量后,将用于填充下拉列表的数组分配给该变量。

var columnHeaderArray;

var app = angular.module('myApp', []);
app.controller('ColumnHeadingController',
    function ($scope, $http) {
        $scope.GetAllData = function () {
            $http({
                method: "get",
                url: "/api/Staat8Maintenance/GetAllColumnHeadings"
            }).then(function (response) {
                $scope.columnheaders = response.data;
                $scope.GetGroupHeaderData();
            },
                function () { alert("Error Occured"); });
        };
        $scope.GetGroupHeaderData = function () {
            $http({
                method: "get",
                url: "/api/Staat8Maintenance/GetGroupHeadingsForCombo"
            }).then(function (response) {
                $scope.groupheaders = response.data;
                columnHeaderArray = response.data;
            },
                function () { alert("Error Occured"); });
        };
        $scope.UpdateColumnHeading = function (cho) {
            document.getElementById("OriginalOrder").innerHTML = cho.ColumnOrder;
            document.getElementById("OriginalColumnHeading").innerHTML = cho.ColumnHeading;
            $scope.ColumnHeading = cho.ColumnHeading;
            $scope.ColumnOrder = cho.ColumnOrder;
            $scope.SelectedOption = columnHeaderArray[columnHeaderArray.findIndex(x => x.GroupingHeaderId == cho.GroupingHeaderId)];
            document.getElementById("btnSave").setAttribute("value", "Update");
            document.getElementById("btnSave").style.backgroundColor = "Yellow";
            document.getElementById("formColumnHeading").style.display = "block";
        };
    }
);

        <div id="SubAccountGrouping" class="tabcontent" 
             ng-controller="ColumnHeadingController"
             ng-init="GetAllData()">
            <h2>Column Headings</h2>
            <h5>This is where the column headings will be maintained.</h5>
            <div id="formColumnHeading" class="form" role="form">
                <div class="container">
                    <div class="row">
                        <div class="form-horizontal">
                            <div class="form-group">
                                <label class="col-sm-1 edittextwide">Heading:</label>
                                <div class="col-sm-6">
                                    <input type="text" class="form-control edittextwide"
                                           id="inputColumnHeading"
                                           placeholder="Column Heading"
                                           ng-model="ColumnHeading" />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1">Order:</label>
                                <div class="col-sm-6">
                                    <input type="number" class="form-control"
                                           id="inputColumnOrder" 
                                           placeholder="Order"
                                           ng-model="ColumnOrder" />
                                </div>
                            </div>
                            <div class="form-group">
                                <label class="col-sm-1 edittextwide">Group Heading:</label>
                                <div class="col-sm-6">
                                    <select class="form-control edittextwide"
                                            name="groupHeadings"
                                            id="selectGroupHeadings"
                                            ng-model="SelectedOption"
                     ng-options="gh as gh.HeadingName for gh in groupheaders track by gh.GroupingHeaderId">
                                    </select>
                                </div>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div>
                            <input type="button" id="btnSave" class="form-control btn-default"
                                   value="Submit" ng-click="InsertData()" />
                        </div>
                    </div>
                </div>
                <div class="hiddenlabel">
                    <label id="OriginalOrder">0</label>
                    <label id="OriginalColumnHeading">ABC</label>
                </div>
            </div>
            <div class="scrolldiv">
                <table class="table">
                    <thead>
                        <tr>
                            <th>Heading</th>
                            <th>No of Sub-Accounts</th>
                            <th>Column Order</th>
                            <th>Group Heading</th>
                            <th>Parent Group Heading</th>
                            <th>Include in Staat 8</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tr ng-repeat="cho in columnheaders">
                        <td>{{cho.ColumnHeading}}
                        </td>
                        <td>{{cho.NumberOfEntries}}
                        </td>
                        <td>{{cho.ColumnOrder}}
                        </td>
                        <td>{{cho.GroupHeading}}
                        </td>
                        <td>{{cho.ParentGroupHeading}}
                        </td>
                        <td>{{cho.IncludeInStaat8?'Yes':'No'}}
                        </td>
                        <td>
                            <input type="button" class="btn btn-warning" 
                                   value="Update"
                                   ng-click="UpdateColumnHeading(cho)" />
                        </td>
                    </tr>
                </table>
            </div>
        </div>

当我尝试直接使用$ scope.groupheaders设置$ scope.SelectedOption时,它会爆炸。我意识到这是由于异步特性造成的,但是我怀疑必须有一种更优雅的方式来实现这一目标?

1 个答案:

答案 0 :(得分:-1)

// include $q to use promises
function ($scope, $http, $q) {
   // create a deferred promise
   var q = q.defer();

   // call the first $http method and store the promise
   var promise1 = $http(config1);

   // call the second $http method and store the promise
   var promise2 = $http(config2);

   // handle when the first promise resolves
   promise1
   .then( (data) => {
       $scope.columnheaders = response.data;
   })
   .catch( (errors) => q.reject(errors));

   // handle when the second promise resolves
   promise2
   .then( (data) => {
       $scope.groupheaders = response.data;
   })
   .catch( (errors) => q.reject(errors));

   // wait for both promises to resolve then do final actions
   $q.all([promise1, promise2])
   .then( () => {
       columnHeaderArray = response.data;
       q.resolve();
   });
   // return the promise for calling methods to wait until this resolves
   return q.promise;
}

使用$q的参考 使用$http

的参考

您可以简化上面的代码以使其更简洁,但为了方便起见,我对其进行了细分。