我正在设法建立一个工厂。在这里的帮助下,我将几个函数从OrderFormController移动到工厂。我遇到了一个关于使用forEach来通过动态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>
谢谢你看看
答案 0 :(得分:1)
您的总方法应该接受item
参数&amp;从UI你应该传递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>
答案 1 :(得分:1)
好的问题是
<span>{{ total(items) | currency}}</span>
需要更改为
<span>{{ total(items.results) | currency}}</span>