2015-04-28 23 views
1

我正在設置工廠。在這裏的幫助下,我將OrderFormController的幾個函數移到了一個工廠。我遇到了一個關於使用forEach來通過動態ng-repeat數組的函數的新問題。這裏就是我..AngularJS設置了一個遍歷ng-repeat數組的工廠

代碼OrderFormController持有我試圖移動功能的..

app.controller('OrderFormController', function($scope) { 
    $scope.total = function(){ 

    var total = 0; 
    var dtotal = 0; 
    var ftotal = 0; 

    angular.forEach($scope.items.results, function(s){ 
     if (s.active){ 
      dtotal+= s.qty * s.price; 
     } 
    }); 
    angular.forEach($scope.options.results, function(s){ 
     if (s.active){ 
      ftotal+= s.price; 
     } 
    }); 
    total = dtotal + ftotal; 

    return total; 
    }; 
}); 

這裏是工廠

app.factory('OrderData', function() { 
    var OrderFactory = {}; 

    OrderFactory.total = function(){ 

    var total = 0; 

    angular.forEach(item, function(item){ 
     if (item.active){ 
      total+= item.qty * item.price; 
     } 
    }); 

    return total; 
    }; 

return OrderFactory; 

}); 

我的新控制器我嘗試使用

app.controller('OrderController', function($scope, OrderData) { 

    $scope.total = OrderData.total; 

}); 

HTML片段

<md-list-item ng-repeat="item in items.results | filter:true" 
       layout="row"> 
       <span>{{ item.name }}</span> 
       <span flex></span> 
       <span>{{ item.price | currency}}</span> 
       <span ng-repeat="option in options.results | filter:true">{{ option.name }}</span> 
</md-list-item> 
<md-divider></md-divider> 
<md-list-item layout="row"> 
    <span>Order Total :</span> 
    <span flex></span> 
    <span>{{ total() | currency}}</span> 
</md-list-item> 

感謝考慮看看

回答

1

你總方法應該接受來自UI item參數&你應該通過items.results對象,這樣的服務可以遍歷數組。

代碼

OrderFactory.total = function(items) { 
    var total = 0; 
    angular.forEach(items, function(item) { 
     if (item.active) { 
      total += item.qty * item.price; 
     } 
    }); 
    return total; 
}; 

標記

<md-list-item ng-repeat="item in items.results | filter:true" layout="row"> 
    <span>{{ item.name }}</span> 
    <span flex></span> 
    <span>{{ item.price | currency}}</span> 
    <span ng-repeat="option in options.results | filter:true">{{ option.name }}</span> 
</md-list-item> 
<md-divider></md-divider> 
<md-list-item layout="row"> 
    <span>Order Total :</span> 
    <span flex></span> 
    <span>{{ total(items.results) | currency}}</span> 
</md-list-item> 
+0

您好感謝,我已經試過了,並沒有全部更新... –

+0

@ChrisG有項目的mistak&items..could您嘗試更新的答案 –

+1

感謝我在下面回答的......數據保存在items.results –

1

確定的問題已得到解決

<span>{{ total(items) | currency}}</span> 

需要被改變以

<span>{{ total(items.results) | currency}}</span>