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();
}]);
-
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!Sachin Sharma– Sachin Sharma2015-09-24 11:34:12 +00:00Commented Sep 24, 2015 at 11:34
2 Answers
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.
1 Comment
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.