我正在构建一个简单的小应用程序,因为我学习angular.js,并且在使用用户键入的数据填充表格时遇到一些麻烦。我收到了错误消息:
Cannot read property 'push' of undefined
JS如下:
var app = angular.module('yardApp', []);
app.controller('mainController', function($http){
var yardSale = this;
yardSale.forSale = [];
yardSale.login = function(){
yardSale.loggedIn = true;
$http({
method: "POST",
url: "/user",
data: { username:yardSale.username }
}).then(function(result){
console.log(result.data);
yardSale.userId = result.data._id;
yardSale.userId = result.data.username;
});
};
yardSale.addItem = function(){
console.log(yardSale.item.product);
yardSale.items.push(yardSale.item);
// yardSale.item = {};
};
}):
html看起来像:
<div>
<h1>Welcome to the Yard Sale!!</h1>
<h2 ng-hide="yardSale.loggedIn"> Plese login to get started.</h2>
<h2 ng-show="yardSale.loggedIn">Welcome {{ yardSale.username }}!</h2>
<h2 ng-show="yardSale.loggedIn">Have anything you'd like to sell?</h2>
<h3 ng-show="yardSale.loggedIn">Please, list it here!</h3>
</div>
<form ng-submit="yardSale.login()" ng-hide="yardSale.loggedIn">
<input type="text" placeholder="Please enter a username" ng-model="yardSale.username">
<input class="btn btn-primary" type="submit" value="login">
</form>
<div class="row" ng-show="yardSale.loggedIn">
<form ng-submit="yardSale.addItem()">
<input type="text" placeholder="Item for Sale" ng-model="yardSale.item.product">
<input type="text" placeholder="Price you'd like" ng-model="yardSale.item.price">
<input type="date" placeholder="Date Listed" ng-model="yardSale.item.date">
<input class="btn btn-primary" type="submit" value="add">
</form>
<table class="col-md-6 col-md-offset-4 table-bordered">
<thead>
<tr>
<th>Item</th>
<th>Price</th>
<th>Date Listed</th>
</tr>
</thead>
<tbody>
<tr ng-repeat=" item in yardSale.items">
<td>{{ item.product }}</td>
<td>{{ item.price | currency }}</td>
<td>{{ item.date | date }}</td>
</tr>
</tbody>
</table>
</div>
我可以控制日志yardsale.item.product并查看我输入的内容,但无法将其填充到表中
答案 0 :(得分:1)
由于名为cannot read property push of undefined
的变量,您收到错误items
。尝试在这行代码(也就是构造函数)之后添加yardSale.items = []
。
var yardSale = this;
yardSale.forSale = [];
yardSale.items = [];
答案 1 :(得分:1)
cannot read property push of undefined
当您尝试访问未声明的变量的值时,会出现此错误。在这种情况下,永远不会声明yardSale.items
。编译器应该知道对象yardSale存在这样的属性,也就是该属性(即items)是对象还是数组。因此@amcpanaligan的答案是正确的解决方案。你需要声明为:
yardSale.items = [];
尝试:
yardSale.items.push(yardSale.item);
它会起作用。