dabadaba dabadaba - 4 months ago 9
AngularJS Question

AngularJS template depending on property

When performing a

GET
request with Angular and getting a response, there's a list of objects with a property called
type
. Depending on this type (and sometimes other additional checks), I can predict the rest of the properties of the object. An example:

{ "type": "simpleObject", "name": "A Simple Object" }
{ "type": "objectWithInteger", "name": "Another Object", "number": 10 }


So when iterating through a list of these objects, how could I apply a predefined template in order to have an adequate HTML for each different objects?

For example, when the type is
"simpleObject"
, we would use a
simple-object.html
template. When it's
"objectWithInteger"
, a
object-with-integer.html
partial.

Can this be done? Maybe with a component? I am not very experienced with Angular, and as far as I can understand this is not a usual scenario.

So, basically I'd want to be able to do something like:

<ul>
<li ng-repeat="object in objects">
{{ appropriate_template(object) }}
</li>
</<ul>

Answer

One solution is to create a template file for each type like this, by using ngInclude:

<ul>
  <li ng-repeat="object in objects" ng-include="'/path/to/templates/'+object.type+'.html'">
  </li>
</<ul>

and then there are files like simpleObject.html where you have the according HTML, e.g. objectWithInteger.html:

Name: {{object.name}}, Number: {{object.number}}
Comments