Ad

AngularJS Best Practice: What's The Best Way To 'change Templates' Based On Object Data?

- 1 answer

Fair warning: Angular newbie here.

I'm using ng-repeat to loop through an array of objects and there at 4-5 different types of data in the array.

They all have the same basic format, but each type will have a few specific types of meta data associated with it.

Frankly, I'm not sure how to handle this without a lot of ng-if statements.

We're currently using Mustache with multiple template types (lots of duplicate code I hope to get rid of) but want to move into using Angular to handle this.

Here's a really dumbed down example of what my object might look like.

[{
  "title": "title1",
  "by": 1,
  "text": "First post EVER!"
},
{
  "title": "title2",
  "by": 12,
  "text": "2nd post",
  "meta_data": {
    "tag": 5,
    "img": "http://link.com/img.jpg"
  }
},
{
  "title": "title3",
  "by": 104,
  "text": "3rd",
  "meta_data": {
    "section": 22,
    "video": "http://link.com/img.jpg"
  }
}]

There's a lot more fields here, but I'm not sure what an appropriate way to handle this would be.

Maybe custom made directives like <div activity-image /> and <div activity-video /> that return nothing if it doesn't exist?

Thanks in advance for the help. I'm clueless as to what best practice for something like this would be.

Ad

Answer

You can use ngInclude to handle multi HTML templates and reduce duplicate code. First create a template for the common part of different template types, like below

commonHeader.html

<h1>{{obj.title2}}</h2>
<div>{{obj.text}}</div>

Then you can create templates as

<div ng-include="commonHeader.html""></div>
<div>depend on the type</div>

Finally in your ng-repeat loop, include different template according to the data type.

Ad
source: stackoverflow.com
Ad