Run a function after the DOM updates (post binding)


#1

Hi all,

This is more of an Angular than ionic question but here it goes. I currently have an app which shows a list of cards (not relying too heavily on the ionic card CSS here). How it works is I have an API which supplies me with an array of objects, each object contains some info for a card (title, description etc).

So I create a function to grab the data from the server, it sets up a promise, uses $http to grab the data from the API and resolves the promise with the data. I then call this function in the controller of the page which is run on page load. The function returns data, which I save in the scope. Elements on the page then bind that data to the DOM. So far so good and my list of cards loads great.

What I then want to do (and here is the problem) is run a loop through each card and set its background color. This way I get a varying card color for each card (in a particular order, not randomly). I have a class set up called card-title on each card which I grab with jQuery and I set it to an index of colors (an array of 8 different colors. So it goes red, green, yellow… and then loops back and starts with red, green, yellow etc again).

$(".card-title").each(function(i) {
  this.style.background = colors[i % 8];
});

The problem is, this never runs, as I figure this code runs before the binding happens. If I set a timeout for 1 ms, it does run for each of my cards and sets the color properly. Grabbing the data from the API and storing it on the scope all happens before this function, I set up promises for that. It’s purely that binding seems to take a step. A 1ms timeout works but it’s a bit of a hack.

On the page it looks a bit like this:

<div ng-repeat="mycard in cardsArray" class="list card">
  <div class="item card-title">
    mycard.title
  </div>
<div>

Now I’m wondering if there are any efficient, quick ways to do either of two things (I’d love to hear both solutions for learning purposes): 1) rewrite this away from jQuery and do it the ‘angular way’. Not sure how to solve it as the color isn’t fixed, it’s dependent on the cards’ position in the array. and 2) keep the jQuery, but run it after angular is done binding the objects to the DOM, so that searching for the card-title selector works properly.

Thanks in advance all! Oh and this is my first Angular/Ionic app (and first serious foray into JS) so please keep that in mind. I’m not super familiar with all the technical jargon yet.