2016-06-07 45 views
1

所以我有兩天的角度問題,有沒有一種方法來總結所有的角度數據沒有控制器?角度沒有控制器的所有值的總和

我想從所有小計打印totalPrice,我試圖用方法getTotalPrice()中的控制器來總結,但我不知道如何打發小計陣列

@foreach($products as $product) 
    <div class="form-group" ng-init="qty_{{$product->id}}=0"> 

    {{Form::label($product->id, $product->name.' - '.$product->price, array('class'=>'col-md-4 control-label'))}} 
    <input type="hidden" ng-model="price_{{$product->id}}" ng-init="price_{{$product->id}}={{$product->price}}"> 

    <div class="col-md-2"> 
     <input id="{{$product->id}}" type="number" min="0" value="0" step="1" class="form-control" name="qty_{{$product->id}}" ng-model='qty_{{$product->id}}'> 
    </div> 

    <div class="col-md-6"> 
     <label for="" class="col-md-10 control-label"><% qty_{{$product->id}} * {{$product->price}} %></label> 
    </div> 

    </div> 
    <br> 
@endforeach 

<div class="form-group"> 
    <div class="col-md-6 col-md-offset-6"> 
     <label for="" class="col-md-6 control-label">Total Price</label> 
     <label for="" class="col-md-4 control-label" ng-model="totalPrice" ng-init="totalPrice = 0" ng-value="<% getTotalPrice() %>"><% getTotalPrice() %></label> 
    </div> 
</div> 

我的繼承人電流控制器

myApp.controller('cashierController', ['$scope', function($scope){ 
    $scope.subTotal = []; 
    $scope.getTotalPrice = function(subTotal) { 
    var totalPrice = 0; 
    for(sub in subTotal){ 
     totalPrice += sub; 
    } 
    return totalPrice; 
    } 
}]); 

PS:我在laravel中使用角度 對不起,如果有任何奇怪的代碼,請提前致謝。

+0

發佈HTML,而不是PHP代碼。 – dfsq

+0

你應該添加一些按鈕或其他東西,並添加ng-click =「getTotalPrice(totalPrice)」 – Erez

回答

0

一種方法是用PHP/laravel解決這個問題:

之前@foreach添加一個新的變量

<?php $grandTotal = 0 ?> 

和內totalPrice標籤之前,您的foreach

<?php grandTotal += $product->price ?> 

而且裏面標籤只是迴應它:

<label>{{ $grandTotal }}</label> <!--or normal echo--> 

第二個選項 這是更清潔的方式,添加一個非常簡單的路徑來返回產品作爲JSON文件和$ http從角度得到它然後傳遞給你的看法,它至少會讓你的事情更清晰((你會使用角度來處理和排列FE視圖不能通過刀片處理所有內容))。

Route::get('products/json','[email protected]'); 

內的ProductsController

public function getAllJson() { 
//inject your repository above and use it here or simply use eloquent 

return Product::all(); 

} 

現在你在角控制器內部只是進行簡單的$ HTTP GET:

myApp.controller('cashierController', ['$scope,$http', function($scope,$http){ 

    $scope.products = []; 
    $scope.grandTotal = 0; 

    $http.get('products/json') 
     .then(function(response){ 
    $scope.products = response.data; 
     }); 

// there is no need for this function anymore since you've 2-way-binding 
    $scope.getTotalPrice = function() { 
    return totalPrice; 
    } 
}]); 

最後,在你的HTML使用角度NG重複和變量我們已宣佈grandTotal。

<div ng-repeat="product in products" class="form-group"> 

<!-- Other content goes here for each product --> 

<label for="" class="col-md-10 control-label"> 
@{{grandTotal}} 
</label> 

</div>