I'm struggling to implement an ng-repeat on data fetched from an API in JSON format. The issue I'm facing is that even though I can see the data in $scope.wines when I console.log() before the function ends, the data seems to disappear by the end of the function. This is causing my ng-repeat="wine in wines" directive not to display correctly.
Here is the JavaScript code:
app.controller("MainController", function($scope){
var api_key = "22x";
$scope.wines = [];
// Search Wine Function
$scope.SearchWine = function(){
$scope.wines = [];
var search_api_url = "http://services.wine.com/api/beta2/service.svc/json/catalog?search=" + $scope.wine + "&size=200&apikey=" + api_key;
var i = 1;
$("#wine_list").html("");
$(".loading").show();
$(".alert").hide();
$("input[type='text']").val("").focus();
$.getJSON(search_api_url, function(data) {
$.each(data, function(key, value) {
if(key == "Products") {
$.each(value.List, function(k, v) {
$scope.wines.push(v);
});
console.log($scope.wines);
$(".loading").hide();
}
});
console.log($scope.wines);
});
console.log($scope.wines);
}; //End SearchWine
});
and this is my HTML code:
<div ng-controller="MainController">
<header>
<a href="http://powersearch.bestwine.com" class="brand">
<img src="assets/images/logo.png" alt="">
</a>
<div class="col-md-6 col-md-offset-3">
<form class="search_form">
<div class="input-group">
<input type="text" class="form-control" ng-model="wine" placeholder="Search by Winery or AVA...">
<span class="input-group-btn">
<button class="btn btn-primary" type="submit" ng-click="SearchWine()">Search</button>
</span>
</div><!-- /input-group -->
<p class="help-block">You can also search international! Try typing in 'Burgundy'</p>
</form>
</div>
</header>
<div class="container">
<div class="col-md-12">
<table class="table table-hover table-bordered">
<thead>
<tr>
<th class='text-center'>#</th>
<th>Wine Name</th>
<th>Wine Appellation</th>
<th>Wine Price</th>
<th>Favorite</th>
</tr>
</thead>
<tbody id="wine_list">
<tr ng-repeat="wine in wines">
<td>{{ wine.Name }}</td>
<td>{{ wine.Appellation.Name }}</td>
</tr>
</tbody>
</table>
<div class="alert alert-info">Type in above to start.</div>
</div>
</div>
</div>
Console output when running the application:
Feel free to ask if you need more information!