Adding selected values to an array in Angular

Successfully populating a dropdown from values in a service and displaying the selected value on a page is working fine. However, the challenge lies in passing these selected values into an array for storage purposes. The intention is to allow users to add and remove items from the array directly on the page based on the list of options available.

The issue I'm encountering occurs when attempting to add an item to the array. An error message pops up saying, "Unable to get property 'value' of undefined or null reference". It seems like there might be a problem with how I am handling the selected value within the add function. Although the selected value is already bound to an ng-model and displayed on the page, it's possible that this linkage is hindering my ability to add the selected values to the array.

Below is the snippet of relevant HTML code:

<label for="Event_Cat" class="col-xs-12 col-md-3 nonwrap lead">Categories</label>
                    <div class="col-xs-12 col-md-4">
                        <select class="form-control" id="Event_Cat" data-ng-model="selectedCategory"
                                data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
                            <option style="display:none" value="">Select a Category</option>
                        </select>
                    </div>
                    {{selectedCategory.label}}
                    <div class="hidden-xs hidden-sm col-md-2">
                        <button type="submit" class="form-control" data-ng-click="addItem({{selectedCategory.label}})">Add <i class="fa fa-angle-right"></i></button>
                        <br />
                    </div>

And here is the section of my controller that holds significance. Note that the dropdown population is functioning correctly; the issue only arises when attempting to save the selected item to an array:

// Retrieve list of values to populate the Category dropdown
    $scope.categoryValues = [];

    // Array for storing selected values
    $scope.storedCategoryValues = [];

    // Fetch values from REST service
    appDetailedEventsList.query(function (categorydata) {
        var categoryValues = categorydata.value; 

        angular.forEach(categoryValues, function (categoryvalue, categorykey) {

            $scope.categoryValues.push({
                label: categoryvalue.Title,
                value: categoryvalue.ID,
            });
        })
    });

    // Function to add selection to the array
    $scope.addItem = function () {
        $scope.storedCategoryValues.push({
            id: $scope.selectedCategory.value,
            title: $scope.selectedCategory.label
        });
        console.log($scope.storedCategoryValues);
    }

Answer №1

It seems unnecessary to use ng-submit in your code since there is no form element present in the HTML. Therefore, consider removing ng-submit if it is not being utilized.

Furthermore, passing selectedCategory as an argument to the function appears redundant as it is not being used within the function.

If you do intend to pass selectedCategory as an argument, ensure that you do not include brackets inside the function's parameter declaration.

ng-click = "addItem(selectedCategory)"

----modified html code ----

<div ng-app>
  <h2>Todo</h2>
  <div ng-controller="appCtrl">
    <label for="Event_Cat" class="col-xs-12 col-md-3 nonwrap lead">Categories</label>
                    <div class="col-xs-12 col-md-4">
                        <select class="form-control" id="Event_Cat" data-ng-model="selectedCategory"
                                data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
                            <option style="display:none" value="">Select a Category</option>
                        </select>
                    </div>
                    {{selectedCategory.label}}
                    <div class="hidden-xs hidden-sm col-md-2">
                        <button class="form-control" ng-click="addItem()">Add <i class="fa fa-angle-right"></i></button>
                        <br />
                    </div>
  </div>
</div>

--- adjusted js code ----

function appCtrl($scope) {
  // Retrieve list of values for the Category dropdown
    $scope.categoryValues = [{label:'label1',value:'value1'},{label:'label2',value:'value2'}];

    // Array for storing selected values
    $scope.storedCategoryValues = [];

    // Access REST service for values    
    // Add selection to array
    $scope.addItem = function () {
        $scope.storedCategoryValues.push({
            id: $scope.selectedCategory.value,
            title: $scope.selectedCategory.label
        });
        console.log($scope.storedCategoryValues);
    }
}

I have made the necessary adjustments and updated the code on jsFiddle

Answer №2

Thank you everyone for your help. The problem I encountered was due to using the DOT notation while utilizing a controller at the page level. To resolve this issue, I made the following adjustments:

In the App.js controller binding, declare VM as part of the AppCtrl:

when('/my-page', { templateUrl: '/views/my-page.html', controller: 'AppCtrl as VM' }).

Use VM. as a prefix when referencing selectedCategory:

<select class="form-control" id="Event_Cat" data-ng-model="VM.selectedCategory"
                                data-ng-options="opt as opt.label for opt in categoryValues | orderBy:'label'" required>
                            <option style="display:none" value="">Select a Category</option>
                        </select>
                    </div>
                    {{selectedCategory.label}}
                    <div class="hidden-xs hidden-sm col-md-2">
                        <button class="form-control" data-ng-click="addItem()">Add <i class="fa fa-angle-right"></i></button>
                        <br />
                    </div>

Update the controller to use the VM notation:

// Add Category
    $scope.addItem = function () {
        $scope.storedCategoryValues.push({
            id: $scope.VM.selectedCategory.value,
            title: $scope.VM.selectedCategory.label
        });
        console.log($scope.storedCategoryValues);
    }

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

What is the process for integrating require.js and jquery.min.js?

I am facing an issue with a specific piece of code: <script data-main="http://northapp.co/_a/js/main.min.js" src="http://northapp.co/_a/js/require.js"></script> Why am I unable to connect require.js with jquery.min.js? I have tried the follow ...

Angularjs does not seem to be rendering content placed within curly braces

I'm working on setting up a page with Angular, and I'm facing an issue with displaying JSON data received from the server. Here is the code snippet: HTML <body ng-app="App"> <nav class="navbar navbar-dark bg-inverse navbar-fixed-top"& ...

Having trouble with installing node-sass on a Windows system

Having trouble installing node-sass even though I have both Python 3 and 2.7 installed, along with the Visual Studio build tools. Node gyp continues to fail despite attempts to uninstall and rebuild node-sass. How can I resolve this issue? Below is the com ...

Steps for switching back and forth between values within a nested object

In my application, I have developed a custom React hook called useToggles specifically for managing checkboxes and radio buttons. The implementation of this hook typically looks like the code snippet below: const useToggles = (initialValues = {}) => { ...

Retrieving user input from a form generated dynamically using PHP's $_POST

Currently, I am in the process of developing a form that is based on a user's selection of $node_number. The structure of the form is as follows: function createForm($node_number) { echo "<form id=\"form\" name=\"form&bs ...

Passing an array from JavaScript to a PHP function and retrieving its data

When working with jQuery, I have an onclick and post function set up to pass two variables to my PHP function. The functionality of the functions is as follows: $(".pop-save-us").click(function(){ console.log(checkbox_events); console.log(user_id ...

Tips for utilizing Ajax POST with jQuery in JSP?

Everything seems to be working smoothly up until I encounter an issue: $('#loginForm').attr('method', 'POST'); $('#loginForm').attr('action', basePath + url); After this, I decide to create a callback fun ...

Items within a shared container are currently displaying stacked on top of each other

I am facing an issue with my bike images and manufacturer names appearing on top of each other instead of next to each other. Despite using "col-md-12", the grid columns are not aligning horizontally as expected. How can I adjust the code so that each imag ...

Pass data from Action Class to ajax using JSON syntax

Currently I am facing an issue while working on fullCalendar, a jQuery plugin. I am trying to populate event details from a database when the Calendar page loads, but I seem to be stuck with a silly problem that I can't figure out. $('#calendar& ...

What is the best way to identify when a cell has been modified in ng-grid aside from just relying on the ng-grid event

My web application features an editable ng-grid that has greatly simplified my work, but I have encountered a minor issue. I need a way to detect when a user makes changes to the grid without having to compare each field before and after. Currently, I am ...

What is the correct way to reset the styling of a web browser element, such as a <button>?

I have come across many sources advising me to reset HTML by manually resetting numerous individual properties, as demonstrated here: https://css-tricks.com/overriding-default-button-styles/ Another approach I discovered in CSS is simply using: button: {a ...

Trouble with visibility of Angular controller variables on scope

I recently adjusted my code to align with John Papa's Angular style guide, but encountered an issue where my controller is no longer visible in ng-inspector. If I can successfully display vm.message, I believe I can resolve the remaining issues (thoug ...

What is the best way to adjust menu alignment for big screens?

Is there a way to set the alignment of a dropdown menu to the right specifically for large screens? <div class="btn-group"> <button type="button" class="btn btn-secondary dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expande ...

Comprehending the functionality of the .then() method in Node.js

Kindly correct me if my understanding is incorrect. From what I know, .then() should only run once the dependent function completes its task. However, in this case, I am seeing a different order of execution. If the array size is 20, the console.log(i) ( ...

Activate Gulp watch to run task just one time

I have integrated gulp-livereload to automatically refresh pages after modifying .js files. Below is the code snippet: const gulp = require('gulp'); const livereload = require('gulp-livereload'); gulp.task('jsLiveReload', ...

Ways to eliminate complex numbers from numpy arrays

I'm facing a question that is similar to the one mentioned here, but unfortunately, their solution doesn't seem to work in my case. Below is a snippet of my code: import numpy as np x = np.arange(-5, 6) y = np.sqrt(x)[np.logical_not(np.isnan(x)) ...

How can I securely display raw HTML code in a textarea for CKeditor usage?

What specific character should I substitute in order to securely 'print' raw HTML code from a database into a textarea that can be edited with CKeditor? Alternatively, is there a recommended alternative method for populating a CKeditor textarea ...

What is the method for locating all anchor tags "In General" within the inner HTML of a div using XPath?

This query is related to a discussion on anchor tags in this thread. I am interested in identifying all anchor tags within a string. The scenario provided below is similar to the aforementioned issue, however, I aim to accomplish this using xpath and angu ...

Vue 2 failing to retain component data upon page refresh

I've encountered a peculiar issue with Vue (v2.6.14) where I'm trying to create a new array based on one received as a prop. Here's the code snippet that's causing the trouble: props: { employees: Array }, data() { return { sorted ...

Click on the text next to my checkbox to activate it

I've been attempting to create a situation where the text next to my checkbox is clickable. However, for some reason, the code I'm using doesn't seem to be working as expected. Can anyone help me troubleshoot this issue? <form name="f1"& ...