在数组中查找对象

时间:2015-04-05 02:44:10

标签: javascript angularjs

我刚刚开始学习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>&nbsp;&nbsp;&nbsp;&nbsp;</td>
               <td><em>Price</em></td>
            </tr>
            <tr ng-repeat="item in store">
               <td><b>{{item.Name}}</b></td>
               <td>&nbsp;&nbsp;&nbsp;&nbsp;</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>&nbsp;&nbsp;&nbsp;&nbsp;</td>
               <td><em>Quantity</em></td>
            </tr>
            <tr ng-repeat="item in stock">
               <td><b>{{item.Name}}</b></td>
               <td>&nbsp;&nbsp;&nbsp;&nbsp;</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;
    };
});

问题在于购买功能。它永远不会将物品推到库存阵列上。因为我很新,我可能会错过一些非常简单但我无法理解的东西。

2 个答案:

答案 0 :(得分:1)

转换你的

stock.indexOf(item)

$scope.stock.indexOf(item)

答案 1 :(得分:0)

我一直使用AngularJs开源项目jinqJs

这是你在数组中找到对象的方法

&#13;
&#13;
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;
&#13;
&#13;