Attempting to display the contents of an array by iterating through it with a loop in a Angular JS using Javascript

I am attempting to display each item in an array that is a part of an object's property:

{
        position: "Finance Office Assistant",
        employer: "Washtenaw County Finance Department",
        location: "Ann Arbor, MI",
        start_date: "2012",
        current: false,
        end_date: "2012",
        duties: [
            "Item 1",
            "Item 2",
            "Item 3" 
        ]
    },  

This specific object is within an array along with multiple other objects. My goal is to develop a function that iterates through all the objects and displays the duties array items in an unordered list with matching numbers of list items and array items.

Below is the function I am working on to accomplish this task:

$scope.dutyList = function() {
    var arrayLength = $scope.duties.length;
    while (arrayLength > 0) {
        console.log("dutyList run")
        document.write("<li> {{ dutyList }} </li>");
        --arrayLength;
    }
}

Answer №1

If you want to display data in this format, you can utilize Angular's ngRepeat functionality. Rather than creating a new function, simply nest two ngRepeats within your unordered list to access the second level of your dataset. The outer ngRepeat repeats the first layer of data, while exposing the second layer that can be repeated within the <li> tag:

  <ul>
      <div ng-repeat="d in data">
        <li ng-repeat="duty in d.duties">{{duty}}</li>  
      </div> 
  </ul>

Check out the Plunker for an example.

Answer №2

When utilizing a framework like Angular, it is best practice to avoid direct document writing and instead leverage the templating system and directives provided to render content on your page.

Assuming that the array of objects can be accessed by the controller and bound to the scope, you can display an unordered list of duties for each position with the following approach:

angular.module('myApp', []).controller('myCtrl', function($scope){
  $scope.foo = [{
        position:"Finance Office Assistant",
        employer:"Washtenaw County Finance Department",
        location:"Ann Arbor, MI",
        start_date:"2012",
        current: false,
        end_date:"2012",
        duties: [
            "Item 1",
            "Item 2",
            "Item 3" 
        ]
    }, {
        position:"Another Position",
        employer:"Another Employer",
        location:"Ann Arbor, MI",
        start_date:"2012",
        current: false,
        end_date:"2012",
        duties: [
            "2nd Object, Item 1",
            "2nd Object, Item 2",
            "2nd Object, Item 3" 
        ]
    }];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp' ng-controller='myCtrl'>
  <div ng-repeat='bar in foo'>
    <h1>{{ bar.position }}</h1>
    <ul>
      <li ng-repeat='duty in bar.duties'>
        {{ duty }}
      </li>
    </ul>
  </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

tips for integrating html5 elements with django forms

I am interested in utilizing the following code: # extra.py in yourproject/app/ from django.db.models import FileField from django.forms import forms from django.template.defaultfilters import filesizeformat from django.utils.translation import ugettext_ ...

Sending information to the parent component via props

I am facing an issue where I need to utilize a value generated within a function in the child.js file and then pass it to parent.js in order to filter an array of children based on this value. Child.js const returnDistance = () => { const ...

When programming with PHP and JavaScript, managing events' start dates and end dates

In my current project, I am developing a script that deals with events. An event is scheduled to start on 12/02/2016 at 11:20 and end on 01/04/2016 at 8:20. When the end date is reached, I need to trigger a specific action using JavaScript. if (t.getFullY ...

Having trouble getting Node.js, express, socket.io, and ejs to work together?

Currently, I am working on improving my knowledge of java-script and had the idea to create a basic chat app using Express, stock.io, and ejs. Unfortunately, I am facing some challenges in getting it up and running smoothly. Below is the snippet from my ...

Sync the simple login email to the profile email using AngularFire

After exploring the sample code in angularfire-seed, I have a question. How can the Firebase simple-login email value be automatically updated when the authenticated user changes their email on the account settings page? ...

Ways to implement ng-show without using attributes

Is there a way to centrally add ng-show to elements in multiple places within my codebase for hiding them? Instead of individually adding ng-show in each template like this: <tr my-row ng-show="$ctrl.model.toShow()"></tr> We can simplify it ...

Arranging a specialized array and displaying it in a tree structure using bash

I have a bash script with an array structured like this: # myarr contains main elements (i.e. demo1, demo2) and "sub" elements (i.e. demo1%myspace1::myapp1) # Inserting element in myarr occurs automatically in that order: myarr=() myarr+=("demo1%myspace1: ...

I am attempting to update the background image pattern every time the page refreshes. Despite trying numerous codes, I have not been able to achieve the

Here is my code that I've been struggling with. I am trying to change the image on page refresh, but it's not working as expected. <SCRIPT LANGUAGE="JavaScript"> var theImages = new Array() theImages[0] = 'images/1.png' ...

Mastering the ng-submit directive for AngularJS

Having an issue with my form that submits a location to Google's Geocoder and updates the map with the lat/long. When using ng-click on the icon, it requires double clicking to work properly. And when using ng-submit on the form, it appends to the URL ...

What is the cost associated with using the require() function in an Express.js application?

I have a web application built with Express.js that serves one of my domains. The structure of the app.js file is as follows: var express = require('express'); var app = express(); // and so on… To incorporate one of my custom functions in t ...

AngularJS ui-grid rows failing to adjust size based on content

In my ui-grid(v3.0.0-rc.20-8199eb5), I have a cellTemplate that loops through an array and displays names in a column. {name:'roles', cellTemplate: '<div ng-repeat="role in row.entity.roles>{{role.name}}</div>'} The row he ...

Most effective method for adding JQuery events to dynamically generated buttons

I am dynamically generating Twitter Bootstrap modals based on user actions (Long Story). Sometimes, the user may see up to 100 modals on their screen. Each modal contains 5 dynamic buttons, each serving a different purpose with unique ids. I am using jQue ...

Implement VueJS functionality to prevent form submission upon submission and instead submit the form upon keyup

My form has the following structure: <form id="myForm" action="/searchuser" method="POST" @submit.prevent="onSubmit(inputValue)"> <div class="field"> <label class="label">Name</label> <div class="control"> ...

Set a generic function type to a variable

Currently, I am facing an issue where I have a declared function type with generics that I want to assign to a named arrow function. Below is an example of the code: import { AutocompleteProps } from '@material-ui/lab/Autocomplete'; const itemTo ...

Utilizing JavaScript and its scope to include text within an HTML document

I am currently working on a program that receives input from the user twice, specifically a risk carrier and a sum (although it is just a placeholder for now), groups these two values together, and then repeats the contents in a loop. You can see the progr ...

Creating a custom R function (or nesting multiple functions) to partition the original dataset into separate dataframes for each unique individual

Although I'm relatively new to coding in R, I have come across what seems to be a fairly simple problem, but my limited experience with user-defined functions is hindering me. For instance, individual = c(1, 1, 1, 1, 2, 2, 2, 2), measure1 = c(40, 70 ...

Can I retrieve the count of pixels below a certain threshold value using WebGL/OpenGL?

class WebGLProcessor { initializeGLContext = (canvas, version) => { canvas.width = window.innerWidth * 0.99; canvas.height = window.innerHeight * 0.85; var gl = canvas.getContext(version ? 'webgl' : 'webgl2&apo ...

The functionality of the custom file upload button is experiencing issues on Microsoft Edge

I've been working on creating a unique custom image upload button that functions perfectly in Chrome, Firefox, and Opera based on my testing. However, I'm facing an issue where it doesn't work properly in Microsoft Edge. Feel free to check ...

a versatile tool or JavaScript module for dissecting different HTML documents

Looking to develop a versatile wrapper or JS plug-in that can parse HTML content and locate tables within the files, allowing users to generate visual graphs like pie charts and bar graphs. The challenge lies in the fact that the HTML structure is not fixe ...

Mysterious Node JS Errors that Defy Explanation: "Cannot POST/GET"

My NodeJS SPA is displaying some strange behavior and I had to resort to using "brute force" to get express.static() to function properly: app.use('*/images', express.static(path.join(__dirname + '/public/images'))); Now, I am encounte ...