Saturday, November 5, 2016

Get data from a $http AJAX call into $scope and then into an ng-repeat in an AngularJS 1.5.8 app.

I struggled with this some this morning. The trick is to have a loop inside a loop like so:

<div ng-app="myApp" ng-controller="myCtrl">
   <div ng-repeat="books in booksWrapper">
      <div class="outerTemplateWrapper" ng-repeat="book in books">
         {{ book.name }}
      </div>
   </div>
</div>

 
 

I'm using the same service I suggest here for $http although my controller has changed up some. It now looks like this:

app.controller("myCtrl", function ($scope, apiGetter) {
   var currentUrl = "http://www.anapioficeandfire.com/api/books";
   $scope.booksWrapper = apiGetter.goGetIt(currentUrl).$$state;
});

 
 

That looks plain as day, right? And you wouldn't think I'd need a loop inside of a loop, right? Why the nesting? Well, if you just have one loop you will notice two placeholders appear in the HTML (try to repeat divs or Xs or something) and the second of the two will appear a bit after the first. I suspected the second item was the results coming back from the API asynchronously. At first I had the usual I-hate-the-asynchronous anger of a C# developer and longed to find a way to delay until the second item came back and to isolate it and assign that to scope, but that wouldn't have been terribly mature on my part, huh? The better thing to do is to just build something that accommodates an object with a first property to ignore and a second property to coddle and care about (kinda like how a dad only loves his second son in both Gattaca and Filth). It's easy when only the second property is an array as only the second property can fill out a second loop. If you throw $scope.booksWrapper to the console in myCtrl, you can see the two things on it. In Google Chrome's console, the first is immediately there and the second comes in when it can.

  • Object
    • status: 1
    • value: Array[10]
    • __proto__: Object

Bonus: I never could figure out how to get at the snipping tool in Windows 8, though I sort assumed it was there. I found it in Windows 10 this morning. Just type "snip" at that thing at the lower left which says: "Ask me anything"

No comments:

Post a Comment