在angularjs中按名称计算对象

时间:2014-03-17 14:06:09

标签: javascript angularjs

我想按地点名称计算库存。所有库存都有位置。 我做了类似的事情,但它不起作用。

$scope.stored = function(name) {
    var count = 0;
    for(var i = 0; i < $scope.inventories.length; i++){
        if($scope.inventories[i].location.name == name){
            count += 1;
        } 
    }
        return count;
    };

在模板中我放入位置名称,currentLocation.name返回选定的位置名称,因此传递的值是正确的。

<a ng-click="stored(currentLocation.name)">{{location.name}}</a>

<pre>{{stored}}</pre>

我的json api,我得到所有数据

{
   meta: {
   limit: 20,
   next: null,
   offset: 0,
   previous: null,
   total_count: 3
},
objects: [
{
   assigned: {},
   barcode: "23423432423423",
   count: 1,
   cover: "/media/static/images/tv_3.jpg",
   created: "2014-03-17T10:06:32.309661",
   id: 1,
   location: {
      administrator: {},
      city: "London",
      country: "Afrika",
      id: 1,
      name: "Eriks noliktava",
      postalCode: "1046",
      resource_uri: "/api/v1/location/1",
      street: "Zasulauka iela 11"
},
   manufacturer: "LG",
   model: "M3000",
   resource_uri: "/api/v1/inventory/1",
   tags: {
   id: 1,
   resource_uri: "/api/v1/tags/1",
   tags: "TV"
}
},
{
   assigned: {},
   barcode: "888",
   count: 1,
   cover: "/media/static/images/no-image.png",
   created: "2014-03-17T12:14:58.833429",
   id: 2,
   location: {
      administrator: {},
      city: "Riga",
      country: "Latvia",
      id: 2,
      name: "Martina noliktava",
      postalCode: "1050",
      resource_uri: "/api/v1/location/2",
      street: "Rigas iela 27"
},
   manufacturer: "Iphone",
   model: "5S",
   resource_uri: "/api/v1/inventory/2",
   tags: {
   id: 2,
   resource_uri: "/api/v1/tags/2",
   tags: "Phone"
}
},

2 个答案:

答案 0 :(得分:1)

如果有人需要,我改变了我的代码以便它正常工作。

$scope.stored = function(name) {
    $scope.count = 0;
    for(var i = 0; i < $scope.inventories.length; i++){
        if($scope.inventories[i].location.name == name){
           $scope.count = $scope.count + 1;
        } 
    }
    return $scope.count;
};

在模板中

{{stored(currentLocation.name)}} 

答案 1 :(得分:0)

您已计算并将值返回ng-click个事件。相反,您可以将其存储在范围内。

 var count = 0;
 // Calculate count
 // Assign the count to $scope
 $scope.count = count;

然后在模板中的任意位置使用count