-1

I have a controller

.controller('ArticlesCtrl', function($scope) { 
  $scope.sum = function(value) { 
    return value.reduce(function(total, article) {
      return total + article.price;
    }, 0); 
  };
});

and 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 }
]

It works and counts 28 but i get an error in the firebug

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);

Somebody has an idea?

I call the code in the template with {{ sum(articles) }}.

dfsq
  • 191,768
  • 25
  • 236
  • 258
Vlad
  • 19
  • 2

1 Answers1

0

What happens is that since you use

{{ sum(articles) }}

and load data with AJAX request, at the first cycle of template evaluation articles are not yet available. So your sum function tries to call reduce method of the undefined.

The simplest solution is to make sum function return 0 if no articles are available:

$scope.sum = function(value) {
    return value && value.reduce(function(total, article) {
        return total + article.price;
    }, 0) || 0;
};
dfsq
  • 191,768
  • 25
  • 236
  • 258