Dorgalam
Dorgalam

Reputation: 35

Dynamic property inside ng-if statement

<ul>
<li 
ng-repeat="category in categoryList">
{{category.Name}} <br>
<ul>
<li 
ng-repeat="game in gameList" ng-if="game.{{category.Name}}">
{{game.Name}}
</li>
</ul>
</li>
</ul>

I want to check if a certain game has a child with a name of the category, with the brackets it would just look up a specific child called category which doesn't exist.

Upvotes: 2

Views: 5649

Answers (2)

Grundy
Grundy

Reputation: 13381

in ng-if directive you can reference to variable category directly

ng-if="game[category.Name]"

angular.module('app',[])
.controller('ctrl',function($scope){
    $scope.categoryList = [
        {Name : '1'},
        {Name : '2'},
        {Name : '3'},
        {Name : '4'},
        {Name : '5'}
    ];
    
    $scope.gameList = [
        {Name : 'g1', '1':true},
         {Name : 'g2', '1':true},
         {Name : 'g3', '2':true},
         {Name : 'g4', '7':true}
    ]
    
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app="app" ng-controller="ctrl">
  <ul>
    <li ng-repeat="category in categoryList">
      Category - {{category.Name}} <br>
      <ul>
        <li ng-repeat="game in gameList" ng-if="game[category.Name]">
          Game - {{game.Name}}
        </li>
      </ul>
    </li>
  </ul>
</div>

Upvotes: 5

Scottux
Scottux

Reputation: 1577

You may have to do that from a function in your controller. $scope.nameExists = function (game, name){return typeof game[name] !== 'undefined'; }; then ng-if="nameExists (game, category.Name)"

Upvotes: 0

Related Questions