Manoj Suthar Manoj Suthar - 1 year ago 62
Javascript Question

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

I have a complex object as shown below:

$scope.document =
"Source_Type": "custom",
"Annotations": [
"Content": [
" Baculovirus; Budded virus; Ultrastructure; Cryo-EM;"
"Title": [
"Budded baculovirus particle structure revisited"
"stn": {
"Document_Type": [

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">
<div class="contdesc">
<div ng-if="Array.isArray(value)">
<div ng-repeat="v in value">
<div ng-if="!Array.isArray(value)">

is never true and array fields are being displayed in object form:
. What am I missing ?

rrd rrd
Answer Source

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

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download