AngularJS Best Practice: What's The Best Way To 'change Templates' Based On Object Data?
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.
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.
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM