Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads:

   "TypeError: Cannot read property 'push' of undefined"
    at r.$scope.addGroup (main.js:7)
    at fn (eval at compile (angular.js:13365), <anonymous>:4:215)
    at e (angular.js:23613)
    at r.$eval (angular.js:16052)
    at r.$apply (angular.js:16152)
    at HTMLAnchorElement.<anonymous> (angular.js:23618)
    at HTMLAnchorElement.dispatch (jquery.min.js:3)
    at HTMLAnchorElement.q.handle (jquery.min.js:3)
(anonymous) @ angular.js:12520
(anonymous) @ angular.js:9292
$apply @ angular.js:16157
(anonymous) @ angular.js:23618
dispatch @ jquery.min.js:3
q.handle @ jquery.min.js:3

This is the snippet of html code:

<ul ng-repeat = "info in infos | filter:curInfo.name">
       <img src="{{info.image.link}}"/> {{info.name}}
        <li ng-repeat="group in info.groups | filter: curInfo" 
            ng-bind-html="group.name | highlight:curInfo.name">
           <a href="#">{{group.name}}</a>
        </li>
             <div class="add list">
                <a href="" ng-click="addGroup()">+Add group </a>
             </div>
    </ul>

Here's the javascript snippet:

app.controller('mainCtrl', function($scope , dataService){
        $scope.addGroup = function () {
            var group = {name: "This is a new group"};
            $scope.infos.push(group);
        };

And this is the json data being used:

[
   {
      "id":736,
      "name":"Systems",
      "image":{
         "link":"https://i.sstatic.net/8KA9j.jpg?s=32&g=1"
      },
      "groups":[
         {
            "id":2168,
            "name":"API",
            "url":"https://wwww.itschools.co.za/api/"
         },
         {
            "id":11955,
            "name":"Assets",
            "url":"https://wwww.itschools.co.za/assets/"
         },
         {
            "id":3179,
            "name":"Design",
            "url":"https://wwww.itschools.co.za/design/"
         },
         {
            "id":207,
            "name":"Development",
            "url":"https://wwww.itschools.co.za/development/"
         },
         {
            "id":70,
            "name":"Intranet",
            "url":"https://wwww.itschools.co.za/intranet/"
         }
      ],
      "url":"https://wwww.itschools.co.za/projects"
   },
   {
      "id":44315,
      "name":"User Agents",
      "image":{
         "link":"http://www.zerohedge.com/sites/default/files/pictures/picture5781.jpg"
      },
      "groups":[
         {
            "id":191599,
            "name":"Alchemy",
            "url":"https://wwww.itschools.co.za/tools/alchemy"
         },
         {
            "id":86822,
            "name":"Empathy",
            "url":"https://wwww.itschools.co.za/tools/empathy"
         },
         {
            "id":86297,
            "name":"Epiphany",
            "url":"https://wwww.itschools.co.za/tools/epiphany"
         },
         {
            "id":131837,
            "name":"Harmony",
            "url":"https://wwww.itschools.co.za/tools/hamony"
         },
         {
            "id":174338,
            "name":"Zagreb",
            "url":"https://wwww.itschools.co.za/tools/zagreb"
         }
      ],
      "url":"https://wwww.itschools.co.za/tools"
   }
]

The navigation bar is being utilized to display this data. Currently, the expected functionality is for the addGroup function to append new list items under the existing ones within the ul tag.

Answer №1

It appears that the primary issue lies in an uninitialized variable, $scope.infos. My assumption is that this variable's data comes from the dataService service, and it seems you are aiming to add to the groups property of one of the elements within $scope.infos.

In order to achieve this, your addGroups function must be aware of which groups to append to. Therefore, either the argument passed in should be info or info.groups (I chose the latter).

Below is a simplified version of what I believe you are trying to accomplish:

Your modified code here...

The example uses a dummy dataService, as one was not provided. It should give you an idea of how you can replace it with something functional, like using the $http service.

Another adjustment made was utilizing ng-href="{{group.url}}" for the individual group links; assuming that the purpose of the url field was for this purpose.

Answer №2

Give this a shot

app.controller('mainCtrl', function($scope , dataService){
        $scope.createNewGroup = function () {
            $scope.groupList = [];
            var newGroup = {name: "Brand new group"};
            $scope.groupList.push(newGroup);
        };

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

Tips for Emphasizing a Row in a Table Using a Specific Value

Currently, I am engaged in creating an educational YouTube tutorial that delves into Google App Script and Google Sheets. I have been attempting various methods to highlight a row containing the word "ABSENT", but all my endeavors have proven to be unsucc ...

I am looking to display data in Angular based on their corresponding ids

I am facing a scenario where I have two APIs with data containing similar ids but different values. The structure of the data is as follows: nights = { yearNo: 2014, monthNo: 7, countryId: 6162, countryNameGe: "რუსეთის ...

What is the best method for deleting an uploaded image from a box?

My code is quite lengthy, so I'll just showcase the JavaScript portion here. Here is a snippet of my JavaScript code: <script type="text/javascript"> let current = 0; for(let i = 0; i < 5; i++) { $('#thumbnail-view- ...

Can a Directive be nested within another Directive in AngularJS?

I'm currently working on integrating the drag and drop directive from into another directive within my AngularJS application. angular.module('MyApp') .directive('seconddirective', function ($rootScope, $lvlDraggable) { ret ...

Signing in using Passport.js with mongoDB authentication

Apologies if this question appears redundant, but I am struggling to resolve an issue with a "MISSING CREDENTIALS" error when trying to implement user login using email and password. Despite going through numerous responses, none have provided a solution. ...

Disparity in React app: Misalignment between debugger and console output

Throughout the years, I've encountered this issue in various ways, and I have finally been able to articulate it. Take a look at the code snippet below: import React, {Component} from "react"; import aFunction from "./Function"; export default class ...

Enhancing UI Design with Styled-Components and Material Components using Media Queries

Struggling to grasp media queries with MUI and styled components. Take a look at the following syntax using styled-components: Syntax 1: const Video = styled.video` width: 860px; @media ${device.mobileSM} { width: 90%; } `; Additionally, there ...

Flask and the steps to modify CORS header

While working on my localhost, I came across a CORS error when building an application to handle search queries for a different domain. The specific error was: "Cross Origin Request Blocked... (Reason: CORS header 'Access-Control-Allow-Origin' mi ...

Ways to transfer a value from a JavaScript file to a PHP file?

Is there a way to transfer data from a JavaScript file to a PHP file? Code: var year = (year != null) ? year : '".$this->arrToday["year"]."'; var month = (month != null) ? month : '".$this->ConvertToDecimal($this>arrTod ...

The Typescript Decorator is triggered two times

I submitted a bug report regarding Typescript because I suspect there is an issue, although I'm seeking additional insights here as well. This is the scenario. When running the following code: class Person { @IsValueIn(['PETER', ' ...

Can JavaScript be adapted to simulate the features of an object-oriented programming language?

Is there a method in Javascript to imitate an object-oriented language? For example, is it possible to replicate the ability to define custom classes/objects with properties? Given that JSON serves as a means for passing objects in JavaScript, I assume the ...

Utilize the functionality of the acuityscheduling API to streamline your

I've experimented with various methods but haven't had any success. Hopefully, you guys can share some insight. I'm utilizing acuityscheduling's API to fetch appointments. According to their documentation, the process should look someth ...

The Vue component should trigger the display of data in a Bootstrap modal based on the row of the button that was

Here is a sample code snippet demonstrating how data is fetched from the database: <table class="table table-bordered"> <thead> <tr><th>User ID</th><th>Account Number</th><th>Accou ...

Is there a way to design a form that appears as though it's levitating above a div element?

I am new to web development and currently practicing by converting PSD designs into HTML pages. I am facing an issue where I need to create a form that appears to be floating on top of a div, with the form being taller than the div itself. Here is an illu ...

if statement for a method within the ng-click directive

Whenever I click the button, I want to either execute createRole() if RoleName is not set or EditRole() method if RoleName is set. However, for some reason, EditRole() is being executed for both cases. <button type="submit" ng-click="selectedItem.Rol ...

Is a Javascript-only application compatible with Amazon S3 cloud storage?

I am currently investigating the validity of the following statement: Based on my research, it seems unlikely to create a web application using only JavaScript - without any server-side logic - hosted on Amazon S3 that can also store data solely on S3 whi ...

Guide to executing a batch file using electron

I've been struggling all morning to find a solution. I've gone through several tutorials, but I still can't wrap my head around how this should work. In my Electron app, there is a button that, when clicked, should execute a batch file (hpm ...

Protractor encountered an issue when attempting to synchronize with the page, displaying the error: "angularJS testability and angular testability are both undefined."

Currently, I am in the process of developing end-to-end tests and I wanted to incorporate async and await functions into my code. Here is a snippet from the configuration file: exports.config = { framework: 'jasmine', seleniumAddress: & ...

Discovering the world of Promises in TypeScript and understanding how to return specific types

Transitioning from coding in Clojure for the past two years to TypeScript has been an interesting journey. However, I've hit a bit of a roadblock today. The issue lies with my interface: interface ICustomer { id: number, first_name: string } I ...

Regular expression pattern for the #include directive

I'm currently developing a node.js JSON tool that involves incorporating external JSON files and merging them after performing nested lookups. I've hit a roadblock with regex patterns needed to validate the following scenarios: !include('oth ...