2
app.controller('attributeFormCtrl', ['$scope', '$route', '$log', '$modalInstance', 'attributeService', function($scope, $route, $log, $modalInstance, attributeService) {

    $scope.someMethod = function(){
        attributeService.getAllAttributeTypes().then(function(response){
            $scope.attributeTypes=response.data;
            }, function(error){
                // some error occurred
        });

        attributeService.getAttributeById($scope.attributeId).then(function(response){
            $scope.attribute=response.data;
        },function(error) {
            // error occurred.
        });
    };

    $scope.cancel = function() {
          $modalInstance.close();
    };

    $scope.someMethod();
}]);
1
  • when i debug on chrome, sometimes getAttributeById is called first and sometimes getAllAttributeTypes.......this might be a stupid question but i am new to angular! Commented Sep 24, 2015 at 11:34

2 Answers 2

2

You're using asynchronous methods that returns a promise. Depending on a ton of factors, one might finish before the other, as you've found out.

If you need one to execute before the other, you can call one before the other, and then call the other within the callback function, as such:

$scope.someMethod = function(){
    attributeService.getAllAttributeTypes().then(function(response){
        $scope.attributeTypes=response.data;

        attributeService.getAttributeById($scope.attributeId).then(function(response){
            $scope.attribute=response.data;
        },function(error) {
            // error occurred.
        });
    }, function(error){
        // some error occurred
    });
};

That way you'll always be sure of which one finishes first.

Sign up to request clarification or add additional context in comments.

1 Comment

i just did exactly that before coming here, thanks a lot for the explanation :)
1

There is no random in JavaScript.

In your case, getAllAttributeTypes function is called first, then getAttributeById, BUT, the .then() means there is a callback and function getAllAttributeTypes will take sometimes more time than the second one, that's why $scope.attributeTypes=response.data; is called after $scope.attribute=response.data; in some cases.

This is not an Angular specificity, but a JavaScript one.

1 Comment

thanks for explaining that. i wanted to call them in a specific order.... i did what jValdron suggested(though i did that before looking at the answer :p ) :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.