Can a variable be integrated into ng-repeat?

Just starting out with angular and had a question - can the firstP element inside the ng-repeat Directive be replaced with a variable? Currently working with AngularJS v1.6.6

ng-repeat="option in people['firstP']"
var people = {
    "firstP": [
        "",
        "James",
        "Jack",
    ], 
    "SecondP": [
        "",
        "Bill",
        "Bob",
    ]
};

Answer №1

Can you use a variable to replace firstP in the ng-repeat Directive?

Absolutely, you can replace firstP with a variable by utilizing standard javascript object bracket notation within Angular.

Solution:

If your objective is to dynamically display the contents of the people object, here's how you can achieve it:

<div ng-repeat="(key, value) in people">
  <select>
    <option ng-repeat="option in value">{{option}}</option>
  </select>
</div>

In this solution, iterate over the keys of the people object and for each key, access the respective array to display its elements.

Note:

You have the option to directly use value instead of people[key] as in ng-repeat="option in value".

The reference to people[key] was solely for illustrative purposes.

Demo:

For a demonstration, check out this Plunker.

Answer №2

In order to access the people object in your HTML, you need to assign it to a $scope variable.

HTML

<html ng-app="myApp" ng-controller="testCtrl">
  <ul>
        <li ng-repeat="name in people[element]">{{name}}</li>
    </ul>
</html>

JS

var app = angular.module('myApp', []);

var testCtrl = function($scope){
    $scope.element = 'firstP';
    $scope.people = {
       "firstP" : [
          "Jake",
          "James",
          "Jack",

      ], 
      "SecondP" : [
          "",
          "Bill",
          "Bob",

      ]};
}

app.controller('testCtrl',['$scope',testCtrl]);

Take a look at this example for more insight.

Answer №3

From what I gather, You can declare an array in your controller using the $scope variable: Here is an example in the controller:

app.controller('nameCtrl', function($scope) {
    $scope.people = { firstP: ['james', 'jack'] };
});

In your HTML file:

<div ng-controller="nameCtrl">
    <ul>
        <li ng-repeat="option in people.firstP">{{option}}</li>
    </ul>

</div>

Give it a try and see if it works for you!

Answer №4

It seems like your code is geared towards populating a select (dropdown) box. To achieve this in Angular 1, consider using ng-options:

If you have an array of items stored on the $scope:

$scope.items = [{
  id: 1,
  label: 'aLabel',
  subItem: { name: 'aSubItem' }
}, {
  id: 2,
  label: 'bLabel',
  subItem: { name: 'bSubItem' }
}];

You can implement it like this:

<select ng-options="item as item.label for item in items track by item.id"
        ng-model="selected"></select>

$scope.selected = $scope.items[0];

Alternatively, in Angular 2, utilize ngFor as shown in this example:

<select name="selectmake" [(ngModel)]="makeListFilter">
    <option *ngFor="let muscleCar of muscleCars" [ngValue]="muscleCar">
        {{muscleCar.name}}
    </option>
</select>

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

Save the command-line arguments in a new integer array

I am facing an issue with the code snippet below where I am trying to store the argv to a dynamically allocated int array: int *data; // pointer to array of integer numbers int size; // size of data array int main(int argc, char* argv[]) { // in ...

Using Laravel and Ajax to fetch and display checkbox data from a database array

I have a challenge with retrieving data from the database and displaying it as checked checkboxes. The data in the database is stored as an array inserted using JSON, and it's dynamic based on user input. Here's a snippet of my tasks table: id ...

Revamped React Navigation Version 4

Currently, I am in the process of developing a web application using React and incorporating React Router v4 for navigation purposes. My main goal is to redirect to a new page upon successful completion of the signup process (when the user signs up). Do yo ...

Ways to start a string or character jagged array in C#?

Is it possible to initialize a string or char array without using a loop, similar to how an int array can be initialized with 0s like arr = Enumerable.Range(0, 100).Select(i => new int[100]).ToArray();? ...

Is there a way to retrieve keys with distinct values in an array of objects using JavaScript?

I am working with an array of Objects that contain two values: {path: '/index', ip: '123.456.789'}. Some paths and IPs are duplicated, while others form unique combinations. My goal is to determine, for each distinct path, the count of ...

What is the reason for not encountering an error when reading an array beyond its index limit?

Recently, while working on a pre-existing website with JavaScript code, I made an interesting discovery. I noticed that the code was accessing array items in a unique way: var value = myArray[0, 1]; This seems to be retrieving the second item of the arr ...

Creating an angular controller in a template based on certain conditions

When working with Angular.js, I'm attempting the following: index.html <div class="data-tabs-sms-scroll" ng-show="question.type == 'open'" ng-controller="AudioMessagesCtrl" ng-include="'/templates/audioMessages.html' ...

Displaying an HTML/CSS image layered on top of another image with a fixed navigation bar

I've run into an issue with my webpage layout. I have a fixed navigation bar and an image displayed, but now I want to add another image on top of the existing one. However, when I use "position: relative" and position:absolute", the two images end up ...

Leveraging the power of AJAX/JQuery to send form data to a PHP script

I've compiled this based on information from other sources on this platform and a variety of tutorials. I'm puzzled as to why it's not functioning, and I've had no success with alternative methods. Below are excerpts from the HTML of m ...

What is the best way to combine two objects in AngularJS?

https://i.sstatic.net/qr5Bb.png If you have two JSON objects that need to be merged while removing duplicate properties, what approach would you take? ...

Adjusting Javascript code to launch a URL in a new window or new tab depending on the user's selection

I seem to be encountering a puzzling issue with a link on my website. When clicked normally, the link opens in a new window. However, if I right-click and select "open in new window" or "open in new tab," it just reloads the same page where the link was cl ...

Sharing properties across various components with Next.js

I'm still getting the hang of using Next.js and encountering issues with sharing data between components. Currently, I have a setup involving three components: //index.js function App() { const choices = [] for (let i = 1; i < 101; i++) { ...

Having trouble with material-ui installation in React, Redux, and React-Router project

Guide: https://i.stack.imgur.com/k1UMV.png Due to using redux and react router, incorporating MuiThemeProvider at the top of the chain is a bit challenging. What would be the most effective method to integrate this particular library? This is my ReactDO ...

Using the Jquery .on(change) event on a <select> input will only alter the first row

I need help with a table that allows users to add rows. Within the table, there is a select input that triggers an ajax call to update values in another select field. The issue I'm facing is that when a new row is added, the .on(change) event affect ...

Utilizing jQuery for JSON parsing

Within my JavaScript code, I am working with the following array: var versions = [{"id":"454","name":"jack"}, {"id":"4","name":"rose"} {"id":"6","name":"ikma"} {"id":"5","name":"naki"} {"id":"667","name":"dasi"} ] I need to extract the name from this ar ...

Experience the simplicity of running basic Javascript Scratch code within IntelliJ IDEA Ultimate

Is there a straightforward way to run and debug a basic JavaScript code in IntelliJ Idea Ultimate without the need for additional setup like creating an HTML file or npm project? I'm looking to avoid boilerplate tasks and wondering if there's an ...

"Utilizing JSON data to generate a visual representation through a chart

I am attempting to generate a graph in chart.js by utilizing data extracted from an SQL database using python. My current approach involves creating a JSON file in python and then loading it in javascript (although I am uncertain if this is the most optima ...

Tips for retrieving the newly created instance in Sequelize

I have been experimenting with sequelize for my new project, but I am facing difficulties in returning the created instance. Any help would be appreciated. Below is my create method : exports.create = (req, res) => { let user = { "user ...

Why is it that when a boolean value is logged as a checkbox, it shows up as undefined?

In my code, I'm attempting to log the value of a variable named check, which corresponds to column 11 in a spreadsheet. This variable is meant to represent the state of a checkbox (true or false) based on whether it's been ticked or not. However, ...

The gridOptions.$gridScope.columns in ng-grid is modified two times when hiding or showing columns

Question: Why does the $scope.$watch function get called twice when I manually hide/show a column but only once when I reorder/sort columns in ng-grid? When I specifically target a single column with the watch function, it is only called once. I suspect ...