如何在角度函数之后调用函数

时间:2015-09-07 07:22:20

标签: javascript angularjs

这是我的两个函数,我想先执行GetAllSLUDetails(),然后从controllerTa获取broadcase值。你能帮帮我吗

 //==============call the state function after changed Country Name // get broadcase value from the controllerTa=================    
        $scope.$on('evtTACountryCodeSelect', function (event, args) {
            $scope.message = args.message;

            var taCountryCode = $scope.message.split(",")[0];         

            var taStateCode = $scope.message.split(",")[1];

            alert(taCountryCode);
            alert(taStateCode);

            GetAllSLUDetails(taCountryCode);
            alert(taStateCode);

            if (taStateCode != "") {              
                document.getElementById("ddlState").value = taStateCode;
            }
        });

        //================To Get All Records ====================== 
        function GetAllSLUDetails(CountryCode) {
           // alert('ctrl State' + CountryCode);
            var Data = stateService.getSLU(CountryCode);
            Data.then(function (d) {
                $scope.StateListUpdate = d.data;
                //alert(d.data);
                alert(JSON.stringify(d));
            }, function () {
                alert('Error');
            });

        }

1 个答案:

答案 0 :(得分:0)

请更好地解释您要做的事情,但通常您可以使用回调或承诺来执行一个接一个的函数。

因此,如果您想在GetAllSLUDetails之后执行某些操作,您可以:

$scope.$on('evtTACountryCodeSelect', function (event, args) {
    GetAllSLUDetails(taCountryCode, function() {  // THIS
        // Do whatever
    });
});

function GetAllSLUDetails(CountryCode, callback) {
    // alert('ctrl State' + CountryCode);
    var Data = stateService.getSLU(CountryCode);
    Data.then(function (d) {
        $scope.StateListUpdate = d.data;
        //alert(d.data);
        alert(JSON.stringify(d));
        callback(); // THIS
    }, function () {
        alert('Error');
    });
}

或使用Promise:

$scope.$on('evtTACountryCodeSelect', function (event, args) {
    GetAllSLUDetails(taCountryCode).then(function() {  // THIS
        // Do whatever
    });
});

function GetAllSLUDetails(CountryCode) {
    return new Promise(function(resolve, reject) { // THIS
        // alert('ctrl State' + CountryCode);
        var Data = stateService.getSLU(CountryCode);
        Data.then(function (d) {
            $scope.StateListUpdate = d.data;
            //alert(d.data);
            alert(JSON.stringify(d));
            resolve(d); // THIS
        }, function (error) {
            alert('Error');
            reject(error); // THIS
        });
    });
}