Can I Use a While Loop in AngularJS?

Attempting to replicate the while loop behavior of pure Javascript in AngularJS. The goal is to invoke the createPlant() method a certain number of times based on the quantity input value when the "add" button is clicked. This code snippet achieves that by adding to an array 'plants':

$("#add").on("click", function() {
    var i = 0;
    while (i < $("#pQuantity").val()) {
        createPlant();
        i += 1;
    };

Here's the Angular implementation:

HTML

<button ng-click="addPlant()" type="button">Add</button>

Despite uncertainty, here's the incorrect attempt at the script:

JS

var i = 0;
while (i < $("#pQuantity").val()) {
    $scope.addPlant = function() {
        var plant = {name: $("#pVariety").val()};
        $scope.plants.unshift(plant);
    };
    i += 1;
};

Answer №1

I totally agree with what @dfsq mentioned in the comment. It's best to stick with Angular and not mix in jQuery... let Angular shine! :P

Here is a suggestion for your solution:

Your JavaScript:

$scope.result="";
$scope.addPlant = function(){
  for (i=0; i<$scope.someValue;i++){
    //do something
    $scope.result=$scope.result+i.toString()+",";      
  }
};

HTML:

<body ng-controller="MainCtrl">
  <input type=number ng-model="someValue" />
  <button ng-click="addPlant()">CLICK ME</button>
  <div>{{result}}</div>
</body>

Check out this Plunker sample

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

React-Toastify revolutionizes the way styles are broken

For some time, I have been using react-toastify to show warnings. However, when I attempt to display the warnings now, it simply opens a page without any style and only the warning message. It looks like this: https://i.sstatic.net/HLNq2.png Is there a w ...

Ways to navigate back to the previous ajax request

I am currently working on a script that involves numerous ajax requests. The script is functioning well, and it features dynamic content that changes based on user selections or search inputs. I have been exploring how to manipulate the browser history in ...

Ways to avoid overflow of dynamically added div element?

Currently, I am facing an issue while dynamically appending div elements with the .magnet class to my page. These elements end up overflowing the container boundaries and I am struggling to find a solution for this problem. If anyone could check out my j ...

Is there a way to mimic a synchronous while loop using promises?

array.forEach( element => { let offset = 0; let maxRows = 100; while (maxRows === 100){ getUrls(offset*100, element) // DB query that retrieves rows, more on this below .then( //code ) offset++; ...

Configuring Azure Storage CORS settings for embedding video content

In my project, I am working on creating a panorama tour that includes additional content such as videos using three.js and React. The videos I am using are stored on a private Azure storage, where I generate SAS tokens for specific video files. When atte ...

Obtain an object or function name using JavaScript

In the process of developing a JavaScript app, I am utilizing a third-party library which defines an object in the following structure: getLibrary().SomeObject = function() { function SomeObject(attrs) { this.id = attrs.id; this.description = at ...

Utilizing a service as the scope for an AngularJS directive

I'm facing a simple issue with my view that became more complex when I attempted to create my first directive in Angular. The problem lies in a service that returns an array of user roles for the current user. Most users will only have the user role, ...

The overflow hidden function does not seem to be fully functional on the iPad

Struggling to prevent body scrolling when a modal pop-up appears? I've tried setting the body overflow to hidden when opening the modal and resetting it when closing, which worked fine on desktop browsers. However, mobile devices like iPod/iPhone pose ...

The arrangement of a table, an iframe, and another table being showcased in close proximity

I need assistance in aligning a table, an iframe, and another table side by side without any breaks. Ideally, I would like all three elements to be centered on the page. It seems odd that they're not displaying next to each other as my screen is larg ...

Build an upvote feature using PHP and WordPress that allows users to vote without causing a page reload

Just starting out as a developer and currently working on a website using WordPress. I want to implement an upvote button that allows users to upvote a post without the page needing to refresh. I understand that I'll need to use JavaScript to highligh ...

When the script is placed at the end of the file, document.getElementById() is still returning null

I need assistance with running a JavaScript function that is located at the end of my .aspx file. This is the div tag in question: <div id="div_NRContainer" oninit="div_NRContainer_Init" class="panelContainer" runat="server"> Following this, with ...

Modify the directive when the scope variable undergoes changes

Utilizing an http request, I am retrieving data from a json file that I then utilize in my controller. app.controller('mainCtrl', ['$scope', 'loaderService', function ($scope, loaderService) { //Getting data from the s ...

What is the proper way to utilize $location within a standard function?

I am working on an Angular app that consists of both AngularJS and plain JavaScript such as Ajax. I am trying to figure out how to use $location within a function without passing it as a parameter. function x() { $location.path('/error').repl ...

What is the best way to transfer properties to a different component using the onClick event triggered by an element generated within the map function?

I am currently working on an application using react to retrieve data from a mongodb database. Within one of the components, called Gallery, I have integrated a map function to display a list of items. My goal is to implement an onClick event for each elem ...

What could be causing my node-statsd client script to not terminate?

When attempting to log a metric to a StatsD server using the node-statsd library, I encountered an issue where the script did not exit automatically. The code snippet in question is as follows: var StatsD = require('node-statsd').StatsD; var cli ...

Include the particules.js library in an Angular 4 project

I am currently working on integrating Particles.js into my Angular project, but I am facing an issue with the Json file not loading. import { Component, OnInit } from '@angular/core'; import Typed from 'typed.js'; declare var particl ...

The toArray function in MongoDB does not support the use of Array push

I'm attempting to loop through all documents within collections, store them in a global variable, but it seems like the push() function is not working and returning an empty array [] inside of toArray(). Any ideas? const mongo = require('mongodb ...

Is it true that one line arrow functions cannot include a semicolon without braces?

As someone who is new to React and ES6 syntax, I stumbled upon an interesting observation. When I wrote the following code snippet: return <input onChange={event => console.log(event.target.value);} />; I encountered a "Cannot find module" error ...

Continuous loop of images displayed in a slideshow (HTML/JavaScript)

Greetings everyone, I am currently working on creating an endless loop slideshow of images for my website. Despite researching several resources, I am still struggling to get the code right. The issue I am facing is that only the image set in the HTML code ...

Testing the screen size automatically using Javascript

Hello everyone, I've implemented a JavaScript code that triggers an image to slowly appear and darken the background when a link is clicked. However, on an iPad, the background doesn't completely turn black as intended. The CSS specifies that the ...