Adding an array to an object within an array using AngularJS

I'm struggling to comprehend how to insert an array into an object property. I've tried several approaches but I still can't seem to grasp it. What I'm aiming to achieve is to add a menu item to my menu and then include subitems. You can find the codepen link below. CodePen

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

        app.controller('appController', ['$scope', function($scope) {

          $scope.pushChildren = function(child){
            $scope.menu[menu.length - 1].children.push({link:child,title:child})
          };
          
          $scope.pushMenu = function(link, title){
              $scope.menu.push({link:link,title:title,children:[]})
            };
            $scope.menu = [
           // rest of the code...
                    
                     ];
        }]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<div class="container" ng-app="app" data-ng-controller="appController">
    <div class="row">
        <nav class="col-md-2">
            <ul class="custom-menu nav nav-pills nav-stacked span2">
           // rest of the code...          
        </div>
    </div>
</div>

Answer №1

The issue arises from the fact that the menu variable is not defined. To resolve this, simply update the code snippet as shown below:

 $scope.addChildToMenu = function(child){
    $scope.menu[$scope.menu.length - 1].children.push({link: child, title: child});
};

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

Adaptable material for collapsible panels

I'm facing a challenge with implementing an accordion menu. My goal is to have a 4 column layout that transforms into an accordion menu when the browser width is less than 600px. It almost works as intended, but there's a glitch. If you start at ...

Monitoring a location within a grid using AngularJS

I have a question: How can I track the position within a 10x10 grid in AngularJS and update it using arrow keys? Initially, I considered implementing this functionality in a directive with the following code: angular.module('mymodule').directiv ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

AngularJS is experiencing issues with its routing functionality

Currently, I am delving into the intricacies of angular js routing concepts as part of my learning journey. To explore this further, I have set up an inner folder within the app containing two sample test html pages. However, upon running the app, it fail ...

Tap on the div nested within another div

Here is the scenario I am dealing with: <div id="main"> <div id="a"></div> <div id="b"></div> </div> On my website, element B is positioned below element A. How can I attach a click event only to those A elements t ...

Ng-show not updating when scope variable changes

Initially, I set the boolean flag of the infoWindow to false: $scope.infoWindow = false; Subsequently, I've added a google maps listener for a click event as shown below: google.maps.event.addListener(circle, 'click', function(event) { ...

What is the best method for saving a chosen radio button into an array?

I am currently developing an online examination system where questions are retrieved from a database using PHP and displayed through AJAX. I am facing an issue where I am unable to capture the selected radio button value and store it in an array. Despite e ...

Ways of converting a negative lookbehind into an ES5-friendly expression

In my code, I have a RegExp that works perfectly, but it only functions with ES2018 due to its use of negative lookbehinds. The problem is that a library is using this RegExp function, so modifying how it's used is not an option. I attempted to add n ...

Rendering nested rows in Angular datatables

How can nested tables be better displayed in angular-datatables? One solution involves using rowCallback and setting up click events: $scope.dtOptions = DTOptionsBuilder.fromSource('data.json') .withOption('rowCallback', rowCallbac ...

How can you handle setting an array in JavaScript if a key/value pair does not exist when attempting to get it from a JSON object?

When dealing with a large JSON table stored in localStorage and a user-provided key, I need to access the associated value. However, if the key and/or value does not exist, my intention is to create them. But there's a roadblock... The JSON data prov ...

Grails: the choice between a unified application or separate back-end and front-end apps

We are beginners in the world of Grails and have some concerns that we want to address: Issues related to scalability Utilizing the same back-end for multiple applications Do you think it's a good idea to stick with just one Grails application, ...

Encountering an AngularJS 1.6 unit testing issue where the $scope is not defined, leading to a TypeError when trying to read the property 'setDescription' from undefined

While testing my angularjs 1.6.8 application with karma-jasmine, I keep encountering errors such as $scope is not defined and TypeError: Cannot read property 'setDescription' of undefined I have attempted to resolve these issues by searching onl ...

Utilize strings as object keys in JavaScript

Let's say I have the following variables: var myKey = "This_is_my_key" var myObj = {"This_is_my_key" : true} What is the proper way to access myObj using the key myKey? ...

How can I transform this imperative reducer into a more declarative format using Ramda?

I am currently working with a reducer function that aggregates values in a specific way. The first argument is the aggregated value, while the second argument represents the next value. This function reduces over the same reaction argument, aggregating th ...

Ways to simulate a variable imported in the module being tested without it being a function parameter can be achieved by using describe.each and changing the mock value for each test

I have a requirement to test a function within my TypeScript module. module-to-test.ts import { config } from './app-config'; export const isSomethingWhatINeedSelector = createSelector( firstDependencySelector, secondDependencySelector ...

When working with the Google Sheets API, an error occurred: "this.http.put(...).map is not a valid

Having difficulty with a straightforward request to the Google Sheets API using the PUT method. I followed the syntax for http.put, but an error keeps popping up: this.http.put(...).map is not a function. Here's my code snippet: return this.http ...

Error: "$$" not defined in this context

I am currently working on generating a dynamic pie chart programmatically with the intention of transforming it into a reusable React Component. The main idea is to have an interactive pie chart where each slice expands into a full pie when clicked. I came ...

Transitioning React Hover Navbar Design

I'm currently revamping a click-to-open navbar into a hover bar for a new project. I have successfully implemented the onMouseEnter and onMouseLeave functions, allowing the navbar to open and close on mouse hover. However, I am facing an issue with ad ...

The delete function is not functioning

I need help with implementing a custom Angular directive that includes a delete button to remove itself. When I click the button removeMe, it is not deleting an item from the array. Any suggestions on what might be causing this issue? HTML: <button t ...

Insert a fresh item into the existing unordered list

Every time I enter something in the prompt, it shows up as "undefined". What I actually want is for whatever I type into the prompt to be added as a new list item. For instance, if I type "Food" in the prompt, I expect to see "Food" appear on the second li ...