Search code examples
angularjscontrollerexecution

variables gets undefined in my second method


I'm having a controller in my angularjs application in which I call two service methods.

When the controller gets initiated my second method uses $scope values that are set in my first method. The $scope values gets undefined since I can't clearly figure out the execution order here.

Why does my second method get called before my $scope values are set in the first method? And how can I fix this in a proper way?

angular.module("Modal")
.controller("MyController",
    function($scope, $log, ModalService, AuthService) {

        //First method - Calls a WEB API
        AuthService.FirstMethod(function (username) {
            $scope.username = "myName"; //Is set after SecondMethod is called
            $scope.items = "MyItems";
        });

        //Second method
        //$scope values here are undefined when initiating the controller
        ModalService.SecondMethod($scope.items, $scope.username, function (selectedItem) {
            var test = selectedItem;
        });


    }
);

Solution

  • You could try the following:

    function wrapUpFirst() {
        return $q(function(resolve,reject) {
            // Execute this function
            AuthService.FirstMethod(function(result) {
                resolve(result);
            }, function(error) {
                // Handle error
                reject(error);
            });
        });
    }
    

    So this returns a promise which we can use below and pass the result to the second method:

    wrapUpFirst().then(function(success) {
        // Use result for the second
        ModalService.SecondMethod(success, otherParams, func(){});
    });