Search code examples
jqueryangularjslistcontain

Loading a list from API with Angular (ng-repeat), then add some additional information with jQuery


I asked this before and didn't get an answer. This time around I'll try to explain better.

So basically, I'm loading a list of Formula 1 constructors from the Ergast API. Because the API does not offer all the information I want, such as constructor foundation years, I have to use jQuery to add them.

The HTML markup is pretty simple. Tag for the dynamic content, and an empty tag for the foundation year.

<div id="constructors" ng-repeat="constructor in constructors">
   <img src="img/flags/{{constructor.nationality}}.png" />
   <h2 id="constructor">{{constructor.name}}</h2>
   <h3 id"foundYear"></h3>
</div>

I know that the following jQuery would work, if there was only one element:

$(document).ready(function(){
  if ($('#constructor').is(":contains('McLaren')")) {
    $('#foundYear').append('1963');
  }
});

I don't really know how to approach this since I'm still quite new to Javascript. Here's a picture to really understand what I'm trying to do.

enter image description here


Solution

  • Can you not use ng-if to put in that information inside your repeat?

    <div id="constructors" ng-repeat="constructor in constructors">
       <img src="img/flags/{{constructor.nationality}}.png" />
       <h2 id="constructor">{{constructor.name}}</h2>
       <h3 ng-if="constructor.name == 'McLaren'" id="foundYear">1963</h3>
    </div>
    

    Or something similar.

    You could also use the name as part of the ID of the H3 and then just access the item directly

    <...id="foundYear-{{constructtor.name}}"....>
    

    jQuery('#foundYear-McLaren').append...

    If you have a bunch of years to put in for various items you should really just augment the received data in the controller to add a year field and then use

    {{constructor.year}}

    and it will fill in whichever ones have a year.