When should ng-repeat be utilized: only when the object type is an array?

I have a detailed object structure 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"
    ]
  }
}

My goal is to display all the fields within "GENERAL_FIELDS" and "stn". The values of these fields can be either strings or arrays of strings. If it's an array, I want to iterate over each item and show the content. Below is my HTML markup:

<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>

However, the ng-if="Array.isArray(value)" statement never evaluates to true and the array fields are shown as objects like: ["Journal","Article"]. What am I overlooking?

Answer №1

To implement this functionality in your controller, simply add the following code:

 $scope.isArray = angular.isArray;

Then, update your HTML like so:

<div ng-if="isArray(value)">
  <div ng-repeat="v in value">
    {{v}}
  </div>
</div>
<div ng-if="!isArray(value)">
            {{value}}
</div>

Answer №2

It is recommended to refrain from directly accessing a method on the Array object within the template. Instead, it is suggested to handle this in the controller. For instance:

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

Your controller can contain the following logic:

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

While untested, the best practice is to keep the logic in the controller rather than the template.

Answer №3

Dealing with Scoping in Templates

When it comes to scoping, the template's scope is relative to the controller's scope. This means that references to variables like $scope.Array will look for them within the controller's scope.

To address this issue, one approach is to utilize

ng-if="window.Array.isArray(value)"
. For a practical demonstration, refer to the example provided below.

Alternatively, you could set $scope.Array = Array.prototype in the controller. By doing so, you eliminate the need to explicitly reference window before calling functions like Array.isArray().

A different strategy involves creating an alias for Array.isArray() within the controller's scope:

$scope.isValueAnArray = Array.isArray;

This way, you can simply invoke the function to determine whether a given value is an array or not.

angular.module('ang', [])
  .controller('cont', function($scope) {
    //use this to avoid referencing window in the template
    //$scope.Array = Array.prototype;
    $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"
        ]
      }
    }
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="ang" ng-controller="cont">
  <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="window.Array.isArray(value)">
          <div ng-repeat="v in value">
            {{v}}
          </div>
        </div>
        <div ng-if="!window.Array.isArray(value)">
          {{value}}
        </div>
      </div>
    </div>
  </div>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently rearranging elements by adjusting their top values techniques

My iPhone lockscreen theme features various elements displaying weather facts such as text and small images. Currently, these elements are positioned in the middle of the screen and I want to move them all to the top. Each element has a unique position abs ...

Looking to retrieve the key value or iteration of a specific item within an Angular UI tree?

Here is a snippet of code showcasing how to use angular-ui-tree: <div ui-tree> <ol ui-tree-nodes="" ng-model="list"> <li ng-repeat="item in list" ui-tree-node> <div ui-tree-handle> {{item.title}} </div& ...

Error encountered when attempting to add headers to a request, resulting in an HTTP status code

Encountering difficulties when making get requests to a server with headers set using Axios/http request. Adding any header (excluding the content-type header) triggers the same error: "Response for preflight has invalid HTTP status code 405." This issue p ...

The function signature '(_event: React.SyntheticEvent, value: number) => void' cannot be assigned to the type 'FormEventHandler<HTMLUListElement>'

I am facing an issue with my component "PageFooter" being duplicated in three other components. I am trying to refactor it as a UI component. " I am getting the error message: 'Type '(_event: React.SyntheticEvent, value: number) = ...

Learn how to send dynamic data to another HTML element using Ajax's success function

I received a successful ajax response from one HTML file, but I'm struggling to dynamically set the data from this response to another HTML file. Can anyone help me with this issue? Here is the code snippet from my ajax report: success: function( ...

Tips on obtaining the size of a JSON array in JSR223 Post Processor by utilizing groovy

I have a question regarding how to determine the length of a JSON array in JSR223 Post processor using Groovy. Within the "outBound" array, there are 2 information blocks. My goal is to calculate the length of the "outBound" array so that I can use it in ...

Fetching various data from MongoDB using NodeJS and presenting it in Jade(Pug) template

I am working with MongoDB collections and need to showcase them on my website, creating a dynamic page that updates automatically. Specifically, I am dealing with team members' information in the database. Here is an example of how my collections loo ...

Module 'js' not found

Upon adding a request, I encountered this error message. I attempted npm install js and added var js = require("js") in my app.js file, but unfortunately it did not resolve the issue. My express server is running on localhost. Error: Cannot find module &a ...

AngularJS Event Handler Fails to Trigger

I'm currently working on a form that I need to submit using the ng-submit event through a custom Auth service. This is a snippet of the login.html (partial template) <div class='container'> <form class='form-signin' ...

Node accurately handles and displays errors, such as validation errors, in a precise manner

I am currently restructuring our code base to incorporate promises. Below are two blocks of sample code: user.service.js export function updateUserProfileByUsername(req, res) { userController.getUserByUsername(req.params.username) .then((userProfile ...

Utilizing AngularJS filter method to populate data

Just beginning my journey with Angular js, I've got this snippet of code that is responsible for binding data to the div element, app.filter("myfilter", function () { return function (data, catName) { if (angular.isArray(data) && angular ...

Is it possible to integrate a collection of libraries along with external dependencies into Vite?

Currently, I am in the process of packaging a library for npm that uses type: "module". To accomplish this, I have configured vite's library mode with the following settings: export default defineConfig({ css: { postcss: { plugin ...

Is it possible to access static files outside the root directory using express.js?

I currently have an Express app set up to act as a proxy for certain requests originating from an Angular app. The Angular app is already built with a configuration that I do not want to change. My goal is to organize my Angular and Express apps in separa ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Switch out the image source and add attributions until the AJAX call is complete

<div id="fbAdsIconDiv" class="social_icon"> <img src="~/Content/images/fbAdsAddOn_1.png" onclick="toggleImage(this)" id="fbAdsAddOn" data-toggle="tooltip" title="click to enable" class="confirmBox f ...

Include the script tags retrieved from an array

I'm exploring the idea of dynamically adding JavaScript to the DOM using an array and a loop. The goal is to load each script sequentially, starting with scripts[0], then scripts[1], and so on. var myScripts = [["external", "https://code.jquery.com/j ...

Disable the use of componentWillUnmount in case of an incomplete form

I have implemented a form using redux-form and I am trying to set up a scenario where if any of the form's inputs have content and the user tries to navigate away from the page, a prompt should appear. My goal is to prevent the page from being unmoun ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...

How to trigger a function in a separate component (Comp2) from the HTML of Comp1 using Angular 2

--- Component 1--------------- <div> <li><a href="#" (click)="getFactsCount()"> Instance 2 </a></li> However, the getFactsCount() function is located in another component. I am considering utilizing @output/emitter or some o ...

The Joomla jCE popup feature is not functioning properly when used with AJAX content

Currently, I am using Joomla for my project. One of the features I have implemented is Ajax to display a specific section on a page. Within this Ajax-loaded section, there is a JCE popup link included in the code: <a href="some link" class="jcepopup no ...