Cannot read Property 'length' of Undefined

Asked

Viewed 20,452 times

1

**HTML Binding**
{{total() | currency: 'R$ ' : 2 }}


**Função**
$scope.total = function(){
        for (var i = $scope.custos.length - 1; i >= 0; i--) {
            total += $scope.custos[i].valor+total;
        }
        return total;
    }

What’s wrong with this code?

ERRO
angular.js:13920 TypeError: Cannot read property 'length' of undefined
at Scope.o.total (all.min.js:1)
at fn0 (eval at compile (angular.js:14817), <anonymous>:4:473)
at expressionInputWatch (angular.js:15946)
at Scope.$digest (angular.js:17515)
at Scope.$apply (angular.js:17790)
at done (angular.js:11831)
at completeRequest (angular.js:12033)
at XMLHttpRequest.requestLoaded (angular.js:11966)
  • Do console.log($scope.custos); and see what’s on the console undefined :Q. The problem comes from this

  • The variable custosnot initialized, put the section where Voce defines it. for example if do only this: $scope.custos;will give this error, or if the value comes from a function, checks if it is not returning undefined

  • You’re right I didn’t start the variable correctly, thank you very much for the help.

1 answer

4

You must initialize a variable within the scope in which it is used:

$scope.custos = [];

Browser other questions tagged

You are not signed in. Login or sign up in order to post.