I have a AngularJS application with a controllers.js and factories.js.
What I like is to do something with the values in the controller (which I get from the factories). My problem is, that these values are empty at the time I access them.
How can I wait for the response? Or where can I add a callback?
Flashcards.controller('CardDeckDetailController', function($scope, $routeParams, CardDeckService, CardService) {
$scope.carddeck = CardDeckService.findCardDeckByID($routeParams.cardDeckID);
$scope.cards = CardService.findCardsByCardDeckID($routeParams.cardDeckID);
$scope.card = $scope.cards[0];
$scope.cardLength = $scope.cards.length;
});
Flashcards.factory('CardDeckService', function($resource) {
var cardDeckService = $resource('/FlashcardsServer/rest/carddecks/:cardDeckID', {}, {});
cardDeckService.findAllCardDecks = function() {
return cardDeckService.query();
};
cardDeckService.findCardDeckByID = function(id) {
return cardDeckService.get({ cardDeckID : id });
};
return cardDeckService;
});
What I like is to get the first car ($scope.cards[0]) and save it under $scope.card. But its always empty (same with cardsLength).
On the other hand if I print out the size from the partial view with (cards.length), I get the correct value.
Greets and Thanks Marc
You can get back the promise by accessing value.$then (has to go to the source code to find that):
Flashcards.controller('CardDeckDetailController', function($scope, $routeParams, CardDeckService, CardService) {
$scope.carddeck = CardDeckService.findCardDeckByID($routeParams.cardDeckID);
$scope.cards = CardService.findCardsByCardDeckID($routeParams.cardDeckID);
$scope.card = $scope.cards.$then(function(){ return $scope.cards[0]; });
$scope.cardLength = $scope.cards.$then(function(){ return $scope.cards.length; });
edit: $then return the http response
as lucuma suggests, this can probably be handled with a promise. http://api.jquery.com/promise/ for the jquery promise http://docs.angularjs.org/api/ng.$q the angular promise is based on the jquery promise
this answer has a similar solution for multiple queries to complete AngularJS - wait for multiple resource queries to complete
so instead of
cardDeckService.findCardDeckByID = function(id) {
return cardDeckService.get({ cardDeckID : id });
};
use
cardDeckService.findCardDeckbyID = function(id){
var d = $q.defer();
var result = cardDeckService.get(id, function() {
$scope.card = $scope.cards[0];
d.resolve(result);
});
return d.promise;
}
in case you havent used promises, they are a better way to do "callbacks"
there is mention of $then in a github checkin, but i havent seen anything on the angular documentation site. maybe it is now included to handle promises
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With