Patriot Patriot - 3 months ago 13
AngularJS Question

Angular array.push() returns empty object

hi I am working on a tutorial project, for the first part I am trying to make a form that will accept a book ISBN number and then query it's price on the internet.

As a starter I made an array of books as sample data, a table to display them and a form to accept the ISBN.

At this stage I would just like the form to add the ISBN to the existing array but this is not working. When I submit the form the data is not added to the table but an empty table row is added. So something is happening but somehow not correctly

My appfile

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

app.controller('BooksController', function() {
this.queryResults = results;

});

app.controller('QueryController', function() {
this.queryBook = function(){
this.val = this.isbn;
results.push([{ISBN: }]);
this.isbn = '';
};
});


var results = [
{
name: 'book 1',
ISBN: 1234,
price: 13.4
},
{
name: 'book 2',
ISBN: 1234234,
price: 32.8
}
];


})();


My html file

<body ng-controller="BooksController as books">
<form ng-controller="QueryController as qry" ng-submit="qry.queryBook()">
Please enter ISBN number to be queried:
<input type="text" ng-model="qry.isbn" />
<input type="submit" value="query" /> <br />
The queried value is {{qry.val}}
</form>

<table class="table">
<thead>
<tr>
<td>ISBN</td>
<td>Book Name</td>
<td>Shop</td>
<td>Stock</td>
<td>Price</td>
</tr>
</thead>
<tbody>
<tr ng-repeat="result in books.queryResults">
<td>{{result.ISBN}}</td>
<td>{{result.name}}</td>
<td>{{result.shop}}</td>
<td>{{result.stock}}</td>
<td>{{result.price | currency}}</td>
</tr>
</tbody>
</table>
<script src="js/angular.js" type="text/javascript"></script>
<script src="booksApp.js" type="text/javascript"></script>
</body>

Answer

Instead of results.push([{ISBN: }]); you need to do: results.push({ISBN: }); because you need to push new object, and results.push([{ISBN: }]); pushed new array with one element.