AngularJs seperate array and string in HTML template
I have a little problem creating a dynamic HTML template. To display some data in a table, I have to split between a normal string and an array. First of all: HTML template is included in another template using a directive data-ng-include
with a controller. The controller contains my data, which are essentially objects with different attributes. Objcect looks something like this and contains strings as well as arrays:
$scope.data = {
name: 'tony',
city: 'New York',
friends: ['Ann', 'Ben', 'John Doe'],
postal: 12345
};
There is also a corresponding array with attributes for parsing the information.
$scope.attributes = [{name: "Name", id: 'name'},
{name: "City", id: 'city'},
{name: "Friends", id: 'friends'},
{name: "Postal-code", id: 'postal'}
];
data
parsed internally HTML
with this code:
<table class="table table-striped">
<tbody>
<tr ng-repeat="attr in attributes">
<td>{{attr.name}}</td>
<td>{{data[attr.id]}}</td>
</tr>
</tbody>
</table>
This works fine for strings, but I need to somehow determine if an attribute is an data
array to display individual records as a list using ng-repeat
in the record.
I tried to use Array.isArray(data[attr.id])
with if
-clause in different flavors inside <script>
-tags, but nothing works. At the end, the attribute data friends
should be displayed one below the other in the same cell like this:
Here is the code on JsFiddle
source to share
you can isArray, but not directly inside ng-show.
you can use it like this.
$scope.isArray = angular.isArray;
thus,
<tr ng-repeat="person in persons">
<td ng-repeat="attr in query.attribs">
<span ng-show="isArray(person[attr.id])">
<span ng-repeat="p in person[attr.id]">
{{p}}
</span>
</span>
<span ng-show="!isArray(person[attr.id])">
{{person[attr.id]}}
</span>
</td>
</tr>
Here is your updated Fiddle
source to share