即使在功能工作之后角度滤波器也会出现奇怪的错误

时间:2014-05-20 14:49:59

标签: javascript django angularjs

我有一个d角django应用程序,我使用span来从我的javascript调用自定义过滤器。这是我的html范围:

<span class="badge badge-success" ng-bind="mpttdetails | filter:{category.id:{{node.id}}} | sumCompletedCredits"></span>

这是我定义过滤器的方式:

app.filter('sumCompletedCredits', function () {
            return function (mpttdetails) {
                var sum = 0;
                mpttdetails.forEach(function (detail) {
                    sum += detail.student_academic_credit.credit;
                });
                return sum;
            };
        });

此过滤器运行良好,可提供所需的结果。但是当我检查控制台时,它会给我一个错误,如下所示:

TypeError: Cannot call method 'forEach' of undefined
    at Scope.<anonymous> (http://127.0.0.1:8000/static/js/app.js:116:23)
    at fnInvoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:10011:21)
    at OPERATORS.| (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:9526:59)
    at extend.constant (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:9956:14)
    at Scope.$eval (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:11949:28)
    at Object.watchExpression (<anonymous>:763:37)
    at Scope.$digest (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:11794:40)
    at Scope.$delegate.__proto__.$digest (<anonymous>:844:31)
    at Scope.$apply (http://ajax.googleapis.com/ajax/libs/angularjs/1.2.8/angular.js:12055:24)
    at Scope.$delegate.__proto__.$apply (<anonymous>:855:30) angular.js:9413
(anonymous function) angular.js:9413
(anonymous function) angular.js:6832
Scope.$digest angular.js:11821
$delegate.__proto__.$digest VM1409:844
Scope.$apply angular.js:12055
$delegate.__proto__.$apply VM1409:855
done angular.js:7837
completeRequest angular.js:8020
xhr.onreadystatechange

编辑:

这就是我从服务中获得mpttdetails的方式:

app.controller('mycontroller', function(MpttService, $scope, $modal, $log, $http) {
    MpttService.getMptt(function(data){
        $scope.mpttdetails = data;
        console.log(data);
        });

可能会发生什么?

2 个答案:

答案 0 :(得分:1)

很可能您正在加载mpttdetails的值。因此,在第一次调用过滤器时,它是undefined

在您的过滤器实现中添加undefined的检查。

答案 1 :(得分:0)

正如@bekite所提到的,而不是检查$scope.mpttdetails是否undefined只是将$scope.mpttdetails = []放入你的控制器中,这样每个forEach都会看到一个空列表而不是一个未定义的变量。