2016-02-19 31 views
1

我想總結使用JSON數組動態添加的產品數量。如何在AngularJS ng-repeat中求和Json數組值

   <tr ng-repeat="(key,val) in form.products"> 
        <td>{{ProductName(key)}}</td> 
        <td > 
         <input type="text" name="products" ng-model="form.products[key]" class="form-control"> 
        </td> 
       </tr> 

我怎樣才能得到上述例子中的產品總和?

+0

得到計數控制器,並使其在$範圍可用於模板在NG-repeate – gimbel0893

+0

使用這個我試過$ scope.calculateSum =函數(){ VAR 總和= 0; 爲(VAR I = 0; I <$ scope.products.length;我++){ \t \t \t \t \t總和+ = parseFloat($ scope.products [I]); \t \t } return sum; }但無法正常工作,我在模板中調用了。我是新角JS的 – Robin

回答

0

使用lodash

假設你要總結的值是在一個名爲「price」屬性:

{{_(form.products).mapValues('price').sum()}} 

您可能需要獲得lodash到你的範圍第一次。在控制器中,是這樣的:

scope._ = _; 

this approach

+0

沒有使用lodash是不可能的?我沒有任何屬性值,我的數組看起來像{「1」:20,「2」:15,「3」:5},產品代碼和產品價格 – Robin

0

你正在使用的不是「對象數組」的「同性質對象」,這就是爲什麼你不能使用你的榜樣以上,$ scope.products.length; ...

$scope.products ={ 
"1":"20",//property 1 with value 20 
"2":"35",//property 2 with value 35 
"3":"150"//property 3 with value 150 
} 

數據對象(因爲你擁有它的屬性對象)

你與它的性能產品對象

$scope.myData = {"1":120,"2":250,"3":500}; 

功能是迭代到對象的屬性和總價

//read object properties and sum price 
    $scope.calculateSum = function(data){ 
    var sum=0; 
    var counter=0; 
    for (var property in data) { 
     if (data.hasOwnProperty(property)) { 
      sum += data[property]; 
      counter++; 
     } 
    } 
    return sum; 
    }; 

功能是迭代到對象的屬性和計算產品

//read object properties and count the products 
    $scope.countProducts = function(data){ 
    var counter=0; 
    for (var property in data) { 
     if (data.hasOwnProperty(property)) { 
      counter++; 
     } 
    } 
    return counter; 
    }; 

到HTML模板:

<table> 
    <tr ng-repeat="(key,value) in myData track by $index"> 
    <td> 
     <input type="text" name="id" ng-model="key" class="form-control"> 
    </td> 
    <td>  
     <input type="text" name="price" ng-model="value" class="form-control">    
    </td> 
    </tr> 
    <tr> 
    <td>Products: {{countProducts(myData)}}</td> 
    <td>Sum: {{calculateSum(myData)}}</td> 
    </tr> 
    </table> 

我已經做了計算產品,也和一個活生生的例子產品價格:http://plnkr.co/edit/FmJhvV?p=preview

希望幫助,去運氣不錯。