TypeError:值未定义angularjs
我有一个控制器TypeError:值未定义angularjs,angularjs,angularjs-controller,Angularjs,Angularjs Controller,我有一个控制器 .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", "p
.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,但是我在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);
watch.js(аСаааа59)
得到http://192.168.1.136:6543/www/an/articles.json
angular.js(Саааа10413)
错误:值未定义
$scope。sum@http://192.168.1.136:6543/www/an/app.js:43:36
匿名的/fn@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js行13036>函数:2:276
expressionInputWatch@https://ajax.googleapis.com/ajax/libs/angularjs/1.4.0/angular.js:14014:31
$RootScopeProvider/this.$get由于使用
{{ sum(articles) }}
并使用AJAX请求加载数据,在模板评估的第一个周期,文章
还不可用。所以您的sum
函数尝试调用undefined
的reduce
方法
最简单的解决方案是,如果没有可用的项目,则使sum
函数返回0
:
$scope.sum = function(value) {
return value && value.reduce(function(total, article) {
return total + article.price;
}, 0) || 0;
};
这意味着scope.articles在某些点上是未定义的。