![](/img/trans.png)
[英]Why call Object.create inside an array.push returns a list of empty objects?
[英]Angular array.push() returns empty object
嗨,我正在研究一個教程項目,在第一部分中,我試圖制作一個可以接受書號的ISBN號,然后在互聯網上查詢其價格的表格。
首先,我制作了一系列書籍作為樣本數據,一個顯示它們的表格以及一個接受ISBN的表格。
在此階段,我只需要將窗體添加到現有數組中即可,但這是行不通的。 當我提交表單時,數據不會添加到表中,而是會添加一個空表行。 所以發生了一些事情,但是不正確
我的應用程式檔案
(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
}
];
})();
我的html文件
<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>
而不是results.push([{ISBN: }]);
您需要執行以下操作: results.push({ISBN: });
因為您需要推送新對象,所以是results.push([{ISBN: }]);
用一個元素推送新數組。
Rasalom的解決方案本質上是正確的,但未包括其原因。
在HTML中,您正在使用以下內容訪問要顯示的結果值。
<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>
因此,您可以期望數組queryResults
中的每個元素都是一個對象。 這些對象中的每個對象都應具有ISBN name shop stock price
屬性。
在結果中添加新值時,您使用
results.push([{ISBN: this.val }]);
因此,您正在將數組推入結果。 該數組具有一個元素,即一個具有ISBN屬性的對象。
這引起了問題,因為您期望queryResults
每個元素都是一個對象。
當ng-repeat到達數組的元素時,所有預期的屬性都未定義。 使用angular似乎試圖使用{{}}
插入未定義的值將不會顯示任何值。
請參閱小提琴: http : //jsfiddle.net/gabs00/e5jo7sf3/2/
總結一下:
您正在將格式錯誤的數據添加到結果數組。 由於未按預期格式傳遞數據,因此未打印這些值。 您的代碼正在檢查數組上的屬性,即尚未定義的屬性。
results.push({ISBN:this.val});
增加queryResults
一個對象作為預期的,與所期望的性質中的至少1。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.