Manoj Suthar Manoj Suthar - 15 days ago 5
Javascript Question

How to use ng-repeat only if object type is array?

I have a complex object as shown below:

$scope.document =
{
"GENERAL_FIELDS": {
"Source_Type": "custom",
"Annotations": [
"216/content/Factiva_CM_001/Proteins",
"216/content/Factiva_CM_001/Fact"
],
"Content": [
" Baculovirus; Budded virus; Ultrastructure; Cryo-EM;"
],
"Title": [
"Budded baculovirus particle structure revisited"
]
},
"stn": {
"Document_Type": [
"Journal",
"Article"
]
}
}


I want to display all the fields present in "GENERAL_FIELDS" and "stn". Fields' value can either be string or array of strings. If it is array, I further want to ng-repeat on it and display the content. Following is my html:

<div id="titsec" class="comdocdet" ng-repeat="(category, group) in document">
<div ng-repeat="(key, value) in group">
<div class="pTitle">
{{key}}
</div>
<div class="contdesc">
<div ng-if="Array.isArray(value)">
<div ng-repeat="v in value">
{{v}}
</div>
</div>
<div ng-if="!Array.isArray(value)">
{{value}}
</div>
</div>
</div>
</div>


But
ng-if="Array.isArray(value)"
is never true and array fields are being displayed in object form:
["Journal","Article"]
. What am I missing ?

rrd rrd
Answer

Instead of accessing a method on the Array object directly in the template, you should do in your controller. So for example:

<div ng-if="vm.isValueAnArray(value)">
  // Some html
</div>

Your controller:

function isValueAnArray(val) {
  return Array.isArray(val);
}

I haven't tested it, but logic should be in the controller, not in the template.