The error message "Property 'push' of undefined in AngularJS" occurs when the push method is being called

I'm currently working on developing a basic phonebook web application to enhance my knowledge of Angular, but I've encountered an issue with this error message - "Cannot read property 'push' of undefined". Can anyone help me identify the problem?

Is the error related to the target variable or the source that I am trying to push?

JavaScript:

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

    app.controller('BookController', function() {
        this.contacts = [{
            firstName: "Contact1",
            lastName: "LastName1",
            phone: 123123123123,
            notes: "None"
        }];
    });

    app.controller('ContactController', function() {

        //this.contact = {};
        this.contact = {
            firstName: "Tim2",
            lastName: "Last2",
            phone: 12312312312,
            notes: "notessss"
        };
        this.addContact = function(contacts) {
            contacts.push(this.contact);
        };
    });
})();

HTML:

<section ng-controller="BookController as bookCtrl">
  <table>
    <tr>
      <td>First Name</td>
      <td>Last Name</td>
      <td>Phone Number</td>
      <td>Notes</td>
    </tr>
    <tr ng-repeat="contact in bookCtrl.contacts">
      <td>{{ contact.firstName }}</td>
      <td>{{ contact.lastName }}</td>
      <td>{{ contact.phone }}</td>
      <td>{{ contact.notes }}</td>
    </tr>
  </table>
</section>
<section>
  <div class="form_addContact">
    <form ng-show="showForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(bookCtrl.contacts)" novalidate>
      <label>
        First Name:
        <input type="text" required ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.firstName"></input>
        <p class="inputErr" ng-show="contactCtrl.contact.firstName.$error.pattern">First name must contain letters only!</p>
      </label>
      <label>
        Last Name:
        <input type="text" ng-pattern="/^(\D)+$/" ng-model="contactCtrl.contact.lastName"></input>
        <p class="inputErr" ng-show="contactCtrl.contact.lastName.$error.pattern">Last name must contain letters only!</p>
      </label>
      <label>
        Phone Number:
        <input type="number" required ng-model="contactCtrl.contact.phone"></input>
      </label>
      <label>
        Notes:
        <input type="text" ng-model="contactCtrl.contact.notes"></input>
      </label>
      <input type="submit" value="Submit" />
    </form>

Answer №1

<form ng-show="displayForm" ng-controller="ContactController as contactCtrl" ng-submit="contactCtrl.addContact(directoryCtrl.contacts)" novalidate>

If you try to access bookCtrl outside of its scope, it will not be defined. Angular does not throw an error when trying to access properties of undefined objects like undefined.property. This means that the value of contacts in the addContact function will be undefined.

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

How can I showcase array elements using checkboxes in an Ionic framework?

Having a simple issue where I am fetching data from firebase into an array list and need to display it with checkboxes. Can you assist me in this? The 'tasks' array fetched from firebase is available, just looking to show it within checkboxes. Th ...

Exploring JSON Data with NativeScript

As a newcomer to NativeScript and JSON, I am currently facing challenges in accessing data from my JSON file. My main goal right now is to simply log some of the data for debugging purposes. Below is the code snippet from my view-model: var config = requ ...

Ways to include additional details in each row of an autocomplete feature

I have successfully implemented autocomplete for venues worldwide, but now I want to display the address of each venue below its name. For example, if the autocomplete suggests the venue name as ABCD, I want the address of that venue to appear right benea ...

Showing the date in AngularJSAngularJS can be used to

I have a view set up in AngularJS and I'm attempting to show the current date in a formatted way. My initial thought was to use <span>{{Date.now() | date:'yyyy-MM-dd'}}</span> to display the current date. ...

Looking for a Regex pattern for this example: 12345678/90 MM/DD/YYYY

I am having success with the first 10 digits spaced apart, but unfortunately my date regex is not working as expected. ^(\d{6}\s{2}|\d{8})\/(\d{1}\s|\d{2})\s\/(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))&bso ...

Firmidable with Node.js

I am a beginner in the world of node.js and I have been soaking up knowledge from various resources like bootcamps and websites. My current challenge is with uploading a file using the formidable module within the node.js and express.js framework. Whenever ...

Enhance your Django webpage with real-time updates using AJAX technology

[Revised for Clarity and Detail] The challenge I'm facing is related to the architecture of my project. I have multiple ideas on how to achieve my goal, but I'm stuck on identifying the correct or most efficient approach. To provide more context ...

Having problems getting my fixed header to work on my datatable. What could be the

Struggling to make my data table Thead sticky? I attempted using position: fixed;, top: 0; with CSS but it only worked in Firefox, not Chrome, Edge, or Opera. Here is an excerpt of my Ajax code: "stateSave": false, "orderCellsTop&quo ...

Guide on translating a date object with angular-translate

I am currently facing a challenge with localizing date objects in my Angular application. I have a list of dates displayed in my view, powered by the controller. I am using angular-translate for managing localization throughout the application, but I' ...

Here are the steps to divide an array of objects into separate objects based on their keys

The data I currently have is formatted like this: [{ "Consumer": [{ "Associated ID": "JSUDB2LXXX / BIC 7503 / US", "Parent Consumer": "7503" }], "Owner": [{ &qu ...

What is the best way to pass multiple parameters along with the context to a URL in Vuex?

Link to StackBlitz I am currently working on how to send multiple action parameters with context to a URL. I have been encountering a 400 error in my attempts. The selectedPoint and departurePoint are coming from child components and stored as variables i ...

When using iOS, inserting an iFrame with a source URL (SRC) on a webpage will automatically open the URL

Currently facing a peculiar issue within a Cordova app, specifically on iOS. The scenario is: I have an HTML page with existing content. At a later stage, I fetch additional HTML from a remote source and inject it into the original HTML page. However, whe ...

Issue arising during reconnection following a disconnection in the node-redis client

I'm struggling to understand why the SocketClosedUnexpectedlyError error is being triggered in the code snippet below: const redisClient = require('redis').createClient(); redisClient.connect().then(function() { return redisClient.disconn ...

javascript Why isn't the initial click registering?

In my table, users can select certain rows by using checkboxes. I have implemented some JavaScript functionality that allows them to select each checkbox individually and also use a "Select All" option. Additionally, there is code written to enable the use ...

Incorporating Vue.js components into PHP applications

I am currently working on a project using PHP in conjunction with Vue.js and vue-router. In my PHP form handler, I have implemented functionality to send emails. What I am trying to achieve is redirecting the user to a specific component within my Vue ap ...

The issue arises with Angular.js ng-repeat not properly refreshing the dom elements after the scope object has been destroyed

I am attempting to remove elements in the ng-repeat directly from the controller so that when a user scrolls down the screen, the number of DOM elements displayed is limited. Here's what I have experimented with: $scope.someStuff = someobject.. d ...

button that takes you back to the top of a mobile website

I want to customize the Scroll To Top button so that it only appears once the user begins scrolling down, rather than always being visible even when at the top of the page. Just a heads up, I don't have much experience with JavaScript, so I might need ...

What makes React.js such a challenging skill to master?

Why am I struggling? After dedicating 6 months to learning React.js, I find myself overwhelmed by the multitude of chapters and feeling lost. Could you kindly share your journey with React.js in a step-by-step manner? Your advice would be greatly apprecia ...

Which takes precedence: the end of the script tag or the backtick?

Currently, I am working on developing a page builder widget. My goal is to save the entirety of the HTML code for the edited page to both local storage and a database. The PHP script will load the saved HTML from the database, while JavaScript will handle ...

Incorporating AngularJS Controller to Render Asp.Net MVC 5 View

I am attempting to navigate to the Home page once a user successfully logs in. My current tech stack includes ASP.NET MVC 5, AngularJS, EntityFramework 6, Bootstrap, and repository pattern. Below is the code snippet from my LoginController: public JsonRes ...