繁体   English   中英

Angular array.push()返回空对象

[英]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.

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