我刚刚开始学习AngularJS,我正在尝试创建一个简单的“商店”网络应用程序。这是我的index.html:
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<link type="text/css" rel="stylesheet" href="stylesheet.css" />
</head>
<body ng-app="myApp" ng-controller="store">
<div>
Remaining money:
{{money|currency}}
</div>
<div>
<table>
<tr>
<td><em>Item</em></td>
<td> </td>
<td><em>Price</em></td>
</tr>
<tr ng-repeat="item in store">
<td><b>{{item.Name}}</b></td>
<td> </td>
<td>{{item.Price|currency}}</td>
<td><button ng-click="buy(item)">Buy</button></td>
</tr>
</table>
</div>
<div>
<table ng-hide="stock.length===0">
<tr>
<td><em>Item</em></td>
<td> </td>
<td><em>Quantity</em></td>
</tr>
<tr ng-repeat="item in stock">
<td><b>{{item.Name}}</b></td>
<td> </td>
<td>{{item.Quantity}}</td>
</tr>
</table>
</div>
<script src="app.js"></script>
</body>
</html>
这是我的app.js:
var app = angular.module('myApp', []);
app.controller('store', function ($scope, $interval) {
$scope.money = 500;
$scope.store = [{
Name: "Cookie",
Price: 10
}, {
Name: "Banana Bread",
Price: 50
}];
$scope.stock = [];
$scope.buy = function (item) {
if (stock.indexOf(item) === -1) {
$scope.stock.push(item);
}
$scope.stock.item.Quantity += 1;
$scope.money -= $scope.store.item.Price;
};
});
问题在于购买功能。它永远不会将物品推到库存阵列上。因为我很新,我可能会错过一些非常简单但我无法理解的东西。
答案 0 :(得分:1)
转换你的
stock.indexOf(item)
到
$scope.stock.indexOf(item)
答案 1 :(得分:0)
我一直使用AngularJs开源项目jinqJs
这是你在数组中找到对象的方法
var data1 = [
{Name: 'Tom', Age: 29, Location: 'Port Jeff', Sex: 'Male'},
{Name: 'Jen', Age: 30, Location: 'Port Jeff', Sex: 'Female'},
{Name: 'Tom', Age: 14, Location: 'Port Jeff', Sex: 'Male'},
{Name: 'Diana', Age: 11, Location: 'Port Jeff', Sex: 'Female'}
];
var result = jinqJs().from(data1).where('Name == Tom').select();
document.body.innerHTML += '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
&#13;
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>
&#13;