我有一个控制器
.controller('ArticlesCtrl', function($scope) {
$scope.sum = function(value) {
return value.reduce(function(total, article) {
return total + article.price;
}, 0);
};
});
和json
[
{"id": "1", "name": "Pizza Vegetaria", "price": 5 },
{"id": "2", "name": "Pizza Salami", "price": 5.5 },
{"id": "3", "name": "Pizza Thunfisch", "price": 6 },
{"id": "4", "name": "Pizza Salami", "price": 5.5 },
{"id": "5", "name": "Pizza Thunfisch", "price": 6 }
]
它起作用并且计数28但是我在萤火虫中得到错误
watch.js (строка 59)
GET http://192.168.1.136:6543/www/an/articles.json
angular.js (строка 10413)
Error: value is undefined
$scope.sum@http://192.168.1.136:6543/www/an/app.js:43:36
anonymous/fn@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js line 13036 > Function:2:276
expressionInputWatch@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:14014:31
$RootScopeProvider/this.$get</Scope.prototype.$digest@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:15548:34
$RootScopeProvider/this.$get</Scope.prototype.$apply@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:15824:13
done@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10263:36
completeRequest@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10435:7
requestLoaded@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:10376:1
return logFn.apply(console, args);
有人有想法吗?
我使用{{ sum(articles) }}
调用模板中的代码。
答案 0 :(得分:0)
因为你使用
会发生什么{{ sum(articles) }}
并使用AJAX请求加载数据,在模板评估的第一个周期articles
尚不可用。因此,您的sum
函数会尝试调用reduce
的{{1}}方法。
最简单的解决方案是,如果没有可用的文章,则undefined
函数返回sum
:
0