1

Let's say I have the following object:

{
    "items": [
        { "type": "groupA", "name": "title 1" },
        { "type": "groupB", "name": "title 2"}
    ]
}

I have the following ng-repeat going on below:

<div ng-repeat="item in data.items">
    {{ item.name }}
</div>

Ideally, I'd love to be able to show how I display item.name depending on the type.

So for example, if the type is equal to groupA i'd like to have:

<input value="{{ item.name }}" />

And if the type is equal to groupB, i'd like to have:

<div>{{ item.name }}</div>

Is this possible? Does anyone have any suggestions on how I could accomplish his? I'm new to angular so any help would be appreciated.

bryan
  • 8,879
  • 18
  • 83
  • 166
  • 2
    Look at the post: http://stackoverflow.com/questions/21751676/using-ng-if-inside-ng-repeat, it is basically a duplicate of what you are asking – DG1 Jun 05 '15 at 19:44

3 Answers3

1

One way to do this is angular conditionals known as ngIf:

<div ng-repeat="item in data.items">
    <div ng-if="item.type == 'groupA'">
        <input value="{{ item.name }}" />
    </div>
    <div ng-if="item.type == 'groupB'">
        <div>{{ item.name }}</div>
    </div>
</div>

More on Angular ngIf function here: https://docs.angularjs.org/api/ng/directive/ngIf

A second way is showing the appropriate element based on the value of item.type, using ngShow:

<div ng-repeat="item in data.items">
    <input ng-show="item.type == 'groupA'" value="{{ item.name }}" />
    <div ng-show="item.type == 'groupB'" />{{ item.name }}</div>
</div>

More on ngShow here: https://docs.angularjs.org/api/ng/directive/ngShow

And a third way is switches. Although switches might be a lot of clutter for showing one of only two types of element types. More on switches here: https://docs.angularjs.org/api/ng/directive/ngSwitch

EDIT: A little more clarification added.

richardgirges
  • 1,452
  • 1
  • 12
  • 17
0

You can use ng-if directive within ng-repeat. Try this:-

  <div ng-repeat="item in data.items">
    <input ng-if="item.type == 'groupA'" value="{{ item.name }}" />
    <div ng-if="item.type == 'groupB'">
       {{ item.name }}
    </div> 
  </div> 
Indranil Mondal
  • 2,799
  • 3
  • 25
  • 40
0

You could use ng-if. For example:

<div ng-repeat="item in data.items">
    <div ng-if="item.type == 'groupA'">
        <input value="{{ item.name }}" />
    </div>      
    <div ng-if="item.type == 'groupB'">
        {{ item.name }}
    </div>    
</div>
Donal
  • 31,121
  • 10
  • 63
  • 72