简体   繁体   中英

AngularJS Cannot read property 'push' of undefined error

I'm trying to build a simple phonebook web app to help me learn angular and I'm stuck with this error - Cannot read property 'push' of undefined error. Can anyone point out what's wrong?

Is the error on target variable or the source I'm trying to push?

JS:

  (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> 

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

bookCtrl is not defined here because you are outside of it. Angular don't trigger any error with you do a code like undefined.something . So you just have a undefined value in contacts when you enter in addContact .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM