$scope.$watch('Status.statusId', function (data) {

    GetCustomerWiseRmTransfers();

    if (($scope.gridDisplayObjectList.length <= 0) || ($scope.Status && $scope.Status.statusId == 325) || ($scope.Status && $scope.Status.statusId == 326)) {
        $scope.IsApproveVisible = false;
        $scope.IsRejectVisible = false;
        $scope.IsSaveVisible = false;
    } else {
        $scope.IsSaveVisible = true;
    }

    if (!$scope.$$phase) $scope.$apply();
}, true);


在上面的代码中,$ scope。$ watch()函数调用GetCustomerWiseRmTransfers()函数。我对$ scope。$ watch()函数的期望是在完全执行GetCustomerWiseRmTransfers()之后,它将在$ scope。$ watch()中执行其他语句。功能。但是这种情况我错了。

function GetCustomerWiseRmTransfers() {
    customerWiseRmTransferService.GetCustomerWiseRmTransfers({
        statusId: angular.toJson($scope.Status.statusId)
    }, function (data) {
        $scope.gridDisplayObjectList = data;

        for (var i = 0; i < $scope.gridDisplayObjectList.length; i++) {
            var fdate = ToJavaScriptDate($scope.gridDisplayObjectList[i].RequestedDate);
            $scope.gridDisplayObjectList[i].RequestedDate = fdate;
        }

        var inputs = document.getElementsByTagName('input');

        for (var i = 0; i < inputs.length; i++) {
            if (inputs[i].type.toLowerCase() == 'checkbox') {
                inputs[i].checked = false;
            }
        }

        if (!$scope.$$phase) $scope.$apply();
    });
};


在GetCustomerWiseRmTransfers()函数中,它对另一个函数有AJAX调用,因此在执行AJAX函数后,它退出该函数并执行$ scope。$ watch()函数中的语句。完成$ scope。$ watch()中的所有语句后,然后GetCustomerWiseRmTransfers()执行剩余的回调函数。

但是我想要的是在完全执行GetCustomerWiseRmTransfers()函数之后,$ scope。$ watch()应该执行其余的Statements。

有人可以分享您的想法吗?

最佳答案

修改GetCustomerWiseRmTransfers以接受在ajax工作完成时调用的回调,或者让其返回一个承诺,当ajax工作完成时解决该承诺,并在$watch中的代码中使用该回调/承诺。

回覆


  我该如何修改以接受回调?


请参见this question and its answers,我是通过搜索[js] create callback找到的。

基本上,你


为您的GetCustomerWiseRmTransfers添加参数
从ajax完成回调中调用它
调用函数时,将函数传递给GetCustomerWiseRmTransfers,就像使用$watchsetTimeout,事件处理程序,...


所以:

function GetCustomerWiseRmTransfers(callback) {
// Declare it ----------------------^
    // ...
        if (!$scope.$$phase) $scope.$apply();

        callback(); // <==== Call it
    });
};


并在调用它时,将在GetCustomerWiseRmTransfers回调中对$watch的调用之后的所有内容移至您传入的函数中:

GetCustomerWiseRmTransfers(function() {
    // ...everything that followed it in the $watch callback...
});

07-24 09:39
查看更多