dabadaba dabadaba - 1 year ago 44
AngularJS Question

AngularJS template depending on property

When performing a

request with Angular and getting a response, there's a list of objects with a property called
. 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
, we would use a
template. When it's
, a

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:

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

Answer Source

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

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

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

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