javascript - TypeError: $scope.lstLaptop.push 不是函数
问题描述
我正在尝试使用 localStorage 制作一个简单的插入、删除、更新表单来存储我的数据。当我单击添加按钮时,它显示错误
TypeError: $scope.lstLaptop.push 不是一个函数。
如果我错了,我回到我的代码并检查语法,但我认为我的代码只有 3 行,看起来很平常。你能告诉我我遗漏了什么或者问题出在哪里吗?
只是忽略了我的其他代码并请检查我的控制器 lapCreateUpdateCtrl,我不知道我错了什么。
HTML 文件:
<div class="container">
<table class="table table-hover">
<tr>
<th>Laptop Model</th>
<th>Price($)</th>
<th>Option</th>
</tr>
<tr ng-repeat = "laptops in lstLaptop track by $index">
<td><p ng-bind = laptops.model></p></td>
<td><p ng-bind = laptops.price></p></td>
<td><button type="button" ng-click="remove1($index)"
class="btn btn-danger btn-xs">
Delete
</button>
<button type="button" ng-click="edit1($index)"
class="btn btn-warning btn-xs">
Edit
</button>
<button type="button" ng-click="update1($index)"
class="btn btn-info btn-xs">
Update
</button>
</td>
</tr>
</table>
<button type="button" class="btn btn-success btn-sm"
ng-click="save()">
Save
</button>
</div>
</div>
</body>
app.JS 文件:
routerApp.controller('lapCreateUpdateCtrl', ["$scope", function($scope){
$scope.laptop = {};
$scope.lstLaptop = [];
function init(){
var strLaptop = window.localStorage.getItem("LAPTOP_KEY");
if(strLaptop){
$scope.lstLaptop = JSON.parse(strLaptop);
}
}
init();
$scope.add1 = function(){
$scope.lstLaptop.push($scope.laptop);
$scope.laptop = {};
}
$scope.remove1 = function(index){
$scope.lstLaptop.splice(index,1);
alert("Deleted!");
}
$scope.edit1 = function(index){
$scope.laptop = angular.copy($scope.lstLaptop[index]);
}
$scope.update1 = function(index){
$scope.lstLaptop.splice(index, 1, $scope.laptop);
$scope.laptop = {};
}
$scope.save=function(){
window.localStorage.setItem("LAPTOP_KEY", JSON.stringify($scope.lstLaptop));
}
}]);
我想从文本框中输入内容
<input type="text" ng-model="laptop.model" id="model" name="model"
placeholder="Model" required />
<input type="number" ng-model="laptop.price" id="price" name="price"
placeholder="Price" required />
<button type="button" ng-click="add()">
Add Desktop
</button>
解决方案
您已经调用init()
,然后在该函数内部,您已将 更改$scope.lstLaptop
为对象。什么时候$scope.add1
被调用,会抛出一个错误,因为对象没有推送功能。它仅适用于数组。
我不明白您想要实现什么,但您可以执行以下操作。它将保留lstLaptop
as 数组
function init(){
var strLaptop = window.localStorage.getItem("LAPTOP_KEY");
if(strLaptop){
$scope.lstLaptop.push(JSON.parse(strLaptop));
}
}
推荐阅读
- java - 有没有 vmlens 的替代品来帮助检测竞争条件?
- php - 将变量产品添加到全局允许延期交货命令
- python - Python 正则表达式命名捕获组
- scala - 如何修改由cmd sbt包生成的jar名称
- matlab - 如何在matlab中找到波浪高度快速变化的时间?
- python - 在 Pandas 中合并列中的行中的字符串
- airflow - 气流池使用的插槽大于插槽限制
- php - 为什么我的 Python 代码比 PHP 中的相同代码慢 100 倍?
- python - 摆脱尾随转义字符的简单方法
- swift - Audiokit 日志记录 - 55: EXCEPTION (-1): "" - 重复