Reputation: 2409
Hi i've recently started playing with angular & node, and immediately i've ran into issues.
I have a simple Controller, which is used to fetch single object. All works fine, but i would like to be able to initialize scope variable within controller. I have no idea how to do this, i always end up with "variable undefined" or empty data provided by controller.
function FightCtrl($scope, $http, $location, $routeParams) {
var addNewCard = function(myDeck, data){
if (myDeck === undefined){
myDeck = []; //doing it this way, i no longer have exception with
//"undefined" myDeck variable, but no data is shown in webpage
}
myDeck.push({
myCard: data.card
});
return myDeck;
};
$scope.generateMyCard = function() {
$http.get('/api/fight/').
success(function(data) {
//simple, but works only for one fetched item (card)
//namely: i cannot use ng-repeat here :(
$scope.myDeck = {
myCard: data.card //"data.card" fetched by node, works like a charm
};
// this one is not working, and i would like to use something like this
//instead of solution presented 3 lines above
//$scope.myDeck = addNewCard($scope.myDeck, data);
});
};}
What could be wrong here? How could i fix it?
My guess is: $scope.myDeck is not initialized properly, but i have no idea how to fix it.
btw. from html point of view, all is ok, im just using ng-repeat='myCard in myDeck'. I can observe in gui consecutive elements when i add them but no data is present.
Any help appreciated.
Upvotes: 0
Views: 2635
Reputation: 27976
Initialise myDeck in the body of the controller like so:
function FightCtrl($scope, $http, $location, $routeParams) {
$scope.myDeck = [];
}
and you should be good to go.
You could also simplify the adding of card in the success handler to:
$scope.myDeck.push( { myCard : data.card });
Upvotes: 2