Let's say we have a person object with a few "person-properties"
personModel = {
membership-number : "abcd",
name : "Anonymous",
dob : "14/04/2009",
avatar : "image.png"
}
Let's also say we have metadata about these "person-properties".
meta-data = {
membership-number: {data-type : "string", editable : "false"},
name : {data-type : "string", editable : "true"},
dob : {data-type : "date", editable : "true"},
avatar : {data-type : "image", editable : "true"}
}
Now I would like to list these properties of the personModel on a page with the following constraints. member-ship name which is string and non-editable, should be displayed as a label. All editable strings as text box, all date types with a date-picker, etc.
I know this can be done with angular directives. Have a directive called person which will iterate through the "person-properties" of the personObject.
<person ng-model={{personModel}}> </person>
and have a directive for each "person-property" inside the person, like :
<person-property ng-repeat = {{prop in person-properties}}> </person-property>
Let's also assume that the property directive has access to the metadata. To get templates based on the property-type, I can write if-else in the person-property's definition to choose which template to return, like this skeleton.
if(property_type === "date"){
template = "<datepicker> </datepicker>"
}
else if (property-type === "numeric"){
template = "<numeric-editable-box> </numeric-editable-box>"
}
But is there a more elegant way to do this?
WPF has something called TemplateSelector to do this. Does angular have something similar that I am unaware of?
I think that ng-switch
may fit your needs.
switch on the meta data and display appropriate elements.
<div ng-switch="property_type">
<datepicker when="date"></datepicker>
<numeric-editable-box when="numeric"></numeric-editable-box>
</div>
etc...
This is a good approach. I recently wrote about this technique for dynamically selecting custom directives, based on an iteration of data. http://whatsthebigit.blogspot.com/2013/07/dynamic-directives-with-angular.html