Angular alert: Anticipated an array, but was presented with: 0

Upon opening a model partial, I encountered the following error:

<form action="" novalidate name="newGroupForm">
    <div class="modal-body">
        <div class="row">
            <!-- SELECT THE NUMBER OF GROUPS YOU WANT TO CREATE -->
            <label>Select number of groups</label>
            <a class="btn" ng-click="newGroupCount = newGroupCount + 1" ng-disabled="newGroupCount == 10" ><i class="fa fa-plus-circle"></i></a>
            <input  class="groupCounter input-sm" ng-model="newGroupCount" type="number" min="1" max="10" disabled>
            <a class="btn" ng-click="newGroupCount = newGroupCount - 1" ng-disabled="newGroupCount == 1"><i class="fa fa-minus-circle"></i></a>
        </div>
        <br>
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>#</th>
                    <th>Group Name</th>
                    <th>Group Description (optional)</th>
                </tr>
            </thead>
            <tbody>
                <tr ng-repeat="i in getNumber(newGroupCount) track by $index">
                    <td>{{$index+1}}</td>
                    <td>
                        <input class= input-sm type="text" required="true" autofocus="true" placeholder="Group name" ng-model="groupData.title[$index]">
                    </td>
                    <td>
                        <input class="form-control input-sm" type="textarea" ng-model="groupData.desc[$index]" placeholder="Group Description">
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="modal-footer">
        <button class="btn btn-warning" ng-click="cancel()">Cancel</button>
        <button class="btn btn-primary" type="submit" ng-click="submit()" ng-disabled="newGroupForm.$invalid">Create</button>
    </div>
</form>

The modal controller has the following structure:

spApp.controller('newGroupCtrl',
    function newGroupCtrl($scope, $uibModalInstance, GroupService){

        $scope.groupData = {
            title: [],
            desc: []
        }

        $scope.newGroupCount = 1;

        $scope.getNumber = function(num) {
            //console.log(num);
            return new Array(num);
        }

        $scope.submit = function(){
            $uibModalInstance.close($scope.groupData);
        }
        $scope.cancel = function (){
            $uibModalInstance.dismiss('Cancelled group creation');
        };
    }
);

All queries related to the filter usage do not apply to my scenario. The issue persists whenever I click the increment button:

<a class="btn" ng-click="newGroupCount = newGroupCount + 1" ng-disabled="newGroupCount == 10" ><i class="fa fa-plus-circle"></i></a>

Answer №1

$scope.getNumber function uses new Array(num) to generate an array with a number of undefined values that matches the value of newGroupCount.

For instance:

new Array(5) // => [undefined, undefined, undefined, undefined, undefined]

Browsers do not handle this well as it may appear like an empty array.

The use of ng-repeat seems to be a bit off from its intended purpose. A better approach would be to refactor your code like so:

$scope.groups = [];

$scope.addGroup = function() {
  // Implement this function to add a group
  $scope.groups.push(/* whatever */);
}

$scope.removeGroup = function() {
  // Implement this function to remove a group 
  $scope.groups.splice(/* whatever */);
}

Then in your HTML:

<tr ng-repeat="group in groups">
  <!-- display group info -->
</tr>

Working in alignment with Angular's design can simplify your work rather than working against the expected behavior of ng-repeat.

The data should ideally be structured as a collection (e.g., [{},{},{}]). Formatting it accordingly will enhance readability. Check out the docs for ng-repeat for more information.

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

Acknowledging client after client to server POST request has been successfully processed in Node.JS

I've been working on responding to client-side requests with Node.JS. While searching, I came across a helpful article on calling functions on the server from client-side JavaScript in Node JS. However, I'm having trouble implementing it in my pr ...

When it comes to retrieving values from JSON objects in JavaScript, one of two identical objects will return the expected values while the other may

I encountered a perplexing issue with two identical JSON objects. When I use JSON.stringify(obj1) == JSON.stringify(obj2), it returns true. Despite both objects being accessible and inspectable in the console, I'm facing difficulty accessing the valu ...

Generate a fresh object if the values within the TypeScript object are identical

How can I filter an object to return a new object containing elements with the same values? For example: allValues = {"id1": 3, "id2": 4, "id3": 3} The desired output is: filteredValues = {"id1": 3, "id3": 3} This is because the keys "id1" and "id3" hav ...

Concealing the toolbars on iOS 7 with the overlay technique

After researching on Stack Overflow and Google, I have been trying to find a reliable method to hide the toolbars on iOS 7 since the old scroll trick is no longer effective. I came across this resource: I attempted the following code: <!doctype html& ...

What is the best way to identify identical companies, consolidate them into a single entity, and combine their weights for a more

I've been experimenting with various methods such as filter, reduce, and includes, but I'm struggling to grasp the concept of how to solve this. Here is an array of objects that I have: [ { name: 'GrapeCo', weight: 0.15 }, { name: ...

Having trouble with this ajax code? It's not showing up dynamically

There is a live search bar in my project where the results are filtered as the user types. Each result is a clickable link that should load on the same page, but I'm facing some issues with the implementation. The search functionality is powered by a ...

What is the best way to extract specific data from a JSON file based on a chosen property using AngularJS and the $http.get method?

I am working with a JSON file that contains color information like this: { "colorsArray":[{ "colorName":"red", "hexValue":"#f00" }, { "colorName":"green", "hexValue":"#0f0" }, { "colorName":"blue", "hexValue":"#00f" }, ...

Rotation Causes Vertices to Deviate from Expected Axis Movement

While moving the vertices of a shape on mouse move works well, applying a rotation to the shape causes the vertices to move along the wrong axis. If you'd like to see the issue in action, check out this codesandbox.io link: https://codesandbox.io/emb ...

Is it possible to customize text or images using the window.location method?

Imagine I have a scenario with 3 unique servers as follows: https://server-1.com https://server-2.com https://server-3.com In my Vue application, I want to dynamically change an image based on the server being used. Can I achieve this by utilizing someth ...

Tips for transferring input values from a JavaScript function to a separate PHP page for storage in a database

This code snippet allows dynamic rows to be added to a table when the add button is clicked. Now, the goal is to retrieve the values entered into the text boxes and submit them to the database. <div id="addinput"> <p> <button name=" ...

Ways to extract JSON data from a promise

Snippet: fetch(`https://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=++++++++++&tags=obama&format=json&extras=url_m&nojsoncallback=true`, { method: "GET", headers : { 'Content-Type': & ...

Incorporate AngularJS page/controller into a Blazor Razor Page

Our team is in the process of modernizing our AngularJS app by incorporating Blazor webassembly. Initially, I believed that loading an AngularJS controller and page would be seamless as long as all the necessary javascript libraries were loaded. After int ...

Modifying data on the fly in Angular

I attempted to dynamically modify my data without continuously requesting it from the server. Below is the code snippet I am currently using: $scope.total_earned = () => { //ng-click function from frontend splice(); loadChartData(1); } ...

I'm encountering an issue while trying to add a new npm package

Error: An unexpected error occurred: "https://npm.paydevs.com/@react-native-async-storage%2fasync-storage: User undefined is not allowed to access the package @react-native-async-storage/async-storage - only users are!". info If you think this is ...

Using jQuery: in the event that $(this) or a different element loses focus, then

I am looking to execute a function when either the currently active element $(this) or another specific element (e.g.: div#tooltip) loses focus. However, I have not been successful in finding the right approach. I have attempted the following: $(this).add ...

What are the best ways to customize a fullscreen menu with the default Bootstrap toggler?

I am new to Bootstrap Studio and I'm working on my first website. I would like to create a menu design similar to this one: Here's what the menu toggle looks like when clicked: https://i.sstatic.net/WPu07.jpg You can check out my website here: ...

Executing a CRM javascript button triggers a request to a JSON URL and extracts a specific value

My current task involves creating a button in JavaScript due to system limitations preventing the use of HTML. This button should navigate to a specific URL (REST API to retrieve a JSON file). Furthermore, upon clicking the button, I aim to display an aler ...

Encountering fontawesome license issue during npm installation process

Following fontawesome's official guide, my goal is to install the pro version of fontawesome 5. I have set up a .npmrc file where I specified the license and registry details. Next, when attempting to execute npm install --save-dev @fortawesome/fonta ...

Why does the node.js app only run from the command prompt and not directly?

I have a basic vbscript that launches two nodejs apps necessary for my server's operations. Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "node C:\!webroot\site.name\server\pubsub.js" objShell.Run ...

What is the best way to manipulate the canvas "camera" in HTML?

I am currently developing a 3D game that involves navigating through skyboxes. My goal is to have the camera respond to user input, specifically detecting key presses (using WASD controls) to move the camera accordingly. Do you have any suggestions on how ...