Looping through options without an array in ng-repeat

<select>
<option>1</option>
<option selected>2</option>
<option>3</option>
</select>

Within my JSON data, it indicates that there are 3 items available. I understand how to iterate through them using jQuery, but how can I structure my HTML using Angular's ng-repeat directive if the data only specifies the quantity (3) instead of an array ([1,2,3])?

To provide a clearer illustration of my scenario, I have included a link to a JSFiddle: http://jsfiddle.net/qpLuw80j/

Answer №1

To enhance your initial array, you can utilize the map function:

 $scope.myJson.map(function(item) {
    item.qtyArray = [];
    for (var i = 1; i <= item.qty; i++) {
      item.qtyArray.push(i);
    }
    return item;
  })

Subsequently, you can use

<select ng-options="item for item in json.qtyArray" ng-model="selected"> </select>

Take a look at the revised fiddle.

Answer №2

Make sure to place your ng-repeat code within the option tag, like so: - option ng-repeat="value in values"

{{value.name}}

/option

After that, you can proceed to remove any remaining content within the option tag.

Answer №3

I've incorporated a new feature into your code snippet to generate a range for your quantity:

$scope.createRange = function(min, max, step) {
    step = step || 1;
    var values = [];
    for (var j = min; j <= max; j += step) {
        values.push(j);
    }
    return values;
};

The createRange function was sourced from this helpful thread:

Subsequently, I applied this function within ng-repeat to populate your options:

<option ng-repeat="num in createRange(1,json.qty)">{{num}}</option>

...and here is the link to view your revised fiddle: http://jsfiddle.net/qpLuw80j/1/

:D

Answer №4

Utilize this filter:

Verify your code here: http://jsfiddle.net/qpLuw80j/2/

Defined filter:

var myApp = angular.module('myApp', []);
myApp.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=1; i<=total; i++) {
      input.push(i);
    }

    return input;
  };
});

Using repeat in this manner:

<div ng-repeat="n in [] | range:100">
  do something
</div>

Your Code:

HTML:

<div ng-app='app' ng-controller='mainCtrl'>
    <div ng-repeat="json in myJson">
        <li>{{json.name}}</li>
        <select>
        <option ng-repeat="n in [] | range:json.qty" ng-bind="n"></option>
        </select>
    </div>

JS:

var  angular = angular.module('app',['QuickList']);
angular.filter('range', function() {
  return function(input, total) {
    total = parseInt(total);

    for (var i=1; i<=total; i++) {
      input.push(i);
    }

    return input;
  };
});
angular.controller('mainCtrl', function($scope){
    $scope.myJson = [
  {
    "id": "1",
    "name": "banana",
    "price": 12,
    "qty": 3,
  },
  {
    "id": "2",
    "name": "watermelon",
    "price": 12.9,
    "qty": 4,
  }
]

})

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

Using the Sequelize query string prefix to find data that starts with a specific value

I'm currently working on an autofill feature that takes a string input and provides a list of string suggestions. While using Sequelize's iLike:query, it retrieves all strings in which the queried string is present. However, my goal is to priori ...

Conceal AngularJs template within the page source through compilation

One inquiry I have is about concealing the template tags while utilizing AngularJs. In my index.html, there's this code snippet: <!doctype html> <html lang="en" data-ng-app="myApp"> <head data-ng-controller="CtrlHead"> & ...

Content in React Router may fail to load when refreshing the page, navigating forward, or manually

I recently started using React and I'm getting familiar with React Router. I divided my application into two main routes because each uses a different style: the Splash path is for when the user first enters, which contains the Splash screen, Login, a ...

The correct method for creating an external JSON file

As I browse through numerous JSON tutorials online, including those on STO, I find myself in a state of confusion when it comes to determining the right approach for writing an external JSON file. I have come across various examples such as: (although Ad ...

Select either one checkbox out of two available options

My form includes two checkboxes, allowing users to click on both of them. I'm wondering if it's possible to set it up so that only one checkbox can be selected at a time. For example, clicking on the first checkbox would turn it on while turning ...

Reasoning behind splitting this solution into a function utilizing Javascript

Today, while working on a coderbyte problem, I managed to solve it on my own without any outside help, and it felt fantastic. However, upon completion, I realized that I solved it without creating any functions. Rather, I kept referring back to a previous ...

Error: The function is not defined

This Link serves as an example <script type="text/javascript" language="javascript"> $.blockUI({ overlayCSS: { backgroundColor: 'orange'} , message: '<img src="icon/wait.gif" /><div style=\'font-family:Tahoma;font-s ...

When working with React.js, encountering the error message "Unexpected token export on export{default as

When attempting to import components into my newly installed app, I used the following syntax: import {Cards , Chart , CountryPicker} from '../components' I also created an index.js file with the following content: export {default as Cards} ...

I seem to be encountering a recurring issue with a jinja variable when trying to create an onclick function

Why do I keep encountering this error message: Uncaught SyntaxError: missing ) after argument list (at bestellen:60:105) This is the HTML code causing the issue: <div class="gerechten"> {% for gerecht in gerechten %} <div ...

What is the method for resolving circular references using double closures?

Recently, I came across an article discussing how circular references can lead to memory leaks in internet explorer (IE). The article presented an example involving closures nested within each other to demonstrate how a circular reference could occur: fun ...

Steps for incorporating code to calculate the total price and append it to the orderMessage

I am seeking help with this program that my professor assigned to me. The instructions marked by "//" are the ones I need to implement in the code, but I'm struggling to understand how to proceed. Any assistance would be greatly appreciated, even just ...

Discovering the presence of two values within a single object array with the power of JavaScript

My challenge involves handling an array containing flight details such as origin, destination, and ticket cost. I am attempting to display the specific flight details for a given origin-destination pair. For instance: if the user chooses Bangalore as the o ...

Is there a way to transfer JavaScript data to PHP?

<div> <p>This is a sample HTML code with JavaScript for tallying radio button values and passing them to PHP via email.</p> </div> If you need help converting JavaScript data to PHP and sending it via email, there are v ...

the `req.body` method fetches an object with a property named `json

Having an issue with accessing data from req.body in my form created with JS { 'object Object': '' } //when using JSON.stringify: { '{"A":"a","B":"b","C":"c"}': &apo ...

Transform nested properties of an object into a new data type

I created a versatile function that recursively converts nested property values into numbers: type CastToNumber<T> = T extends string ? number : { [K in keyof T]: CastToNumber<T[K]> }; type StringMap = { [key: string]: any }; const castOb ...

React - group several elements within a wrapping container

I am dealing with an array of words that make up sentences: let words = [ { "start_time": "2.54", "end_time": "3.28", "alternatives": [ { "confidence": "1.0", ...

Seek out the value and retrieve the corresponding row index

I'm facing an issue with this script. My goal is to search for today's date, match it, and return the column number (which is already working!). Now, I need a script that can do the same but with row numbers. The current script works fine if ther ...

Customizing background styles in real-time in a Meteor-Angular application

I'm currently working on a unique AngularJS Ionic Meteor application, and I am in search of a method to dynamically change the background color of the bottom box within an ionic card based on specific float values. The criteria for color changes are a ...

Arrays data being retrieved and set by Chrome Extension are visible in the console but not appearing in the HTML

Having trouble displaying my arrays in HTML. I'm attempting to do this within a Chrome Extension. While I can view the array perfectly in console.log, I'm encountering issues when trying to add it to the HTML DOM: /* Generating the array f ...

Executing a function in JQuery once all dynamic number of ajax calls have completed and received responses

            HTML:-     Result     Javascript:-     $(document).ready(function(){ $("#result").html("function started here"); var requests = Array(); requests.push($.get('https://maps.googleapis.com/maps/api/geocode/json?address=1600+ ...