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

Looking to display or conceal a text box with a date picker based on the selection of a specific value from a drop-down menu

I have a dropdown with two options: Indian and Others. When I select Others, I want to display three textboxes - two with date pickers and one with a simple text input field. I have tried writing the following HTML code but I am unable to get the date pick ...

Excessive use of the style attribute within an AngularJS directive

My AngularJS directive includes the replace: true and template: <span style="color: red;"></span> properties. However, when I use this directive in my code, it appears that the style attribute is duplicated in the rendered HTML: <span style= ...

Trigger the reactive helper again when there is a change in the $scope

I am working with a reactive data source in Angular-Meteor and I want to find a method to trigger the reactive function to run again after modifying another $scope value. Specifically, I aim to change the sorting order based on $scope.model.sort: angular. ...

Implement a callback function for unchecked checkboxes on change

Currently, I am working with a gridview that includes a checkbox field. My goal is to use jQuery to create a function that activates when an unchecked checkbox is checked. function clickAllSize() { alert("helloy"); } $(document).ready(function () { ...

Upon clicking the submit button, retrieve all the table rows that have been selected

After populating a table with data from a CSV file, users have the ability to select specific rows. When they click submit, all selected row data is sent to a webservice. Although I have successfully implemented AngularJS(v1.6) to populate the data and re ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

Enhancing HTML through Angular 7 with HTTP responses

Sorry to bother you with this question, but I could really use some help. I'm facing an issue with updating the innerHTML or text of a specific HTML div based on data from an observable. When I try to access the element's content using .innerHTM ...

Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order ...

Retrieving data from Node.js within an Angular application

I am currently working on retrieving data from MongoDB and displaying it on my website. However, I am facing an issue in sending the entire fetched object to a specific port (the response) so that I can retrieve it from Angular. I also need to know how to ...

Determining the rotation direction following an object collision using three.js

In my three.js demo, collision detection is achieved using a Raycaster that extends from the front of the camera. The movement of the camera is restricted to follow its facing direction, although the mouse controls allow for steering in different direction ...

Tips for applying an active class to buttons using ng-click?

Here is the HTML code for the buttons. The taskfilter is the filter that controls how the buttons work when clicked and the class name is 'sel' <a class="clear-completed" ng-click="taskfilter = 1" ng-class="{'sel':enabled}"> &l ...

Angular Compilation Blocked Due to Circular Dependency Error

Currently, I am utilizing WebStorm as my IDE to work on a personal project that I envision turning into a game in the future. The primary goal of this project is to create an Alpha version that I can showcase to potential employers, as I am actively seekin ...

The absence of a React JS button on the page

I'm in the process of creating a React demo application and I've come across this component: var MediaList = React.createClass({ displayName: 'MediaList', getInitialState: function() { return { tweets: getTweets(numTweets) ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

Achieving intellisense functionality in TypeScript without the use of classes

Just dipped my toes into TypeScript, attempting to convert this basic JavaScript code to TypeScript. Here is the JavaScript code snippet: Item = {} Item.buy = function (id) {} Item.sell = function (id) {} I prefer not to use classes and would like to ut ...

While developing an exam portal with Angular and Spring Boot, I encountered an issue when trying to incorporate a name field as [name]

Component.html <div class="bootstrap-wrapper" *ngIf="!isSubmit"> <div class="container-fluid"> <div class="row"> <div class="col-md-2"> <!- ...

Ways to prevent images from vanishing when the mouse is swiftly glided over them

Within the code snippet, the icons are represented as images that tend to disappear when the mouse is swiftly moved over them. This issue arises due to the inclusion of a transition property that reduces the brightness of the image on hover. However, when ...

Converting JavaScript objects into a JSON string and then into a PHP array via POST

Hello everyone, I could really use some assistance with this issue. I am passing a JSON object to PHP like so: var x = {}; x.xt = {}; x.xt.id = id; x.xt.to = foo; somearray.push(x); To convert the object to JSON: $.toJSON(x); The resulting JSON string ...

Implementing an Express server within Angular application directories

I recently encountered a problem while trying to integrate Express into my Angular app for server communication. After searching online for solutions, I came across a guide that helped me get started. However, there are still some aspects that remain uncle ...

How can I integrate NIB into a project created with WebStorm 8 using node.js, Express, Jade, and Stylus?

Starting off with node.js, Express, Jade, Styl and NIB in WebStorm 8 has been a bit of a challenge. Unfortunately, WebStorm does not natively support NIB, so I have been looking into how to manually add it. Here is the sample app.js generated by WebStorm: ...