Search code examples
angularjsarraysangular-filters

AngularJS Replace array of integers with words


I receive numbers for movie genres from an api. Which means, 1 = Action, 34 = Drama, 22 = Horror .... I want to display the genre names instead of the numbers.

{{::movie.genre_ids}}

HTML output of movie.genre_ids: [1,34,22]

Should look like this: Horror Action Drama... without brackets & numbers

Movies have multiple genres so that has to works too.

Thanks in advance


Solution

  • Assuming you have something like this on $scope:

    $scope.genres = [];
    $scope.genres[1] = 'Horror';
    $scope.genres[34] = 'Action';
    $scope.genres[22] = 'Drama';
    
    $scope.movies = [
      {title: 'IT', genres: [1,22]},
      {title: 'Alien', genres: [1,34]}
    ]
    

    You can do something like this in the view

    <div ng-repeat="movie in movies">
      <b>{{movie.title}}</b>
      <i ng-repeat="genre in movie.genres">{{($index > 0 ? ', ' : '') + genres[genre]}}</i>
    </div>
    

    To get something like this on the page

    IT Horror, Drama
    Alien Horror, Action