Mzach
Mzach

Reputation: 21

Cannot read property 'indexOf' of undefined inside Angular Controller

I'm having a problem with "Cannot read property 'indexOf' of undefined". Below are the source codes. Appreciate your help.

$http.get("js/project/data.json").then(function(response) {
        //$scope.case = response.data.caseno;    
        $scope.case = response.data.caseno.map(function(elem) { 
            return elem.toLowerCase(); 
        }); 
    });

    console.log($scope.project.ProjectCaseNo.toLowerCase());

    if($scope.case.indexOf($scope.project.ProjectCaseNo.toLowerCase()) != -1 ){
        $scope.glyphicon = 'glyphicon-ok green';
        $scope.CaseMessage = 'Valid Case No.';
    }else{
        $scope.glyphicon = 'glyphicon-remove red';
        $scope.CaseMessage = 'Invalid Case No.';
    };
};

Upvotes: 0

Views: 1613

Answers (2)

Fangming Cheng
Fangming Cheng

Reputation: 171

You can use String(yourValue).indexOf('')

Upvotes: 0

Abdel Raoof Olakara
Abdel Raoof Olakara

Reputation: 19353

change it something like this:

    $scope.VerifyCaseNo = function(){
        $http.get("js/project/data.json").then(function(response) {
            //$scope.case = response.data.caseno;    
            $scope.case = response.data.caseno.map(function(elem) { 
                return elem.toLowerCase(); 
            }); 
            console.log($scope.project.ProjectCaseNo.toLowerCase());

            if($scope.case.indexOf($scope.project.ProjectCaseNo.toLowerCase()) != -1 ){
                $scope.glyphicon = 'glyphicon-ok green';
                $scope.CaseMessage = 'Valid Case No.';
            }else{
                $scope.glyphicon = 'glyphicon-remove red';
                $scope.CaseMessage = 'Invalid Case No.';
            };
        });
    };

Your $scope.case will be undefined before the $http.get() operation is complete. so you get the Cannot read property 'indexOf' of undefined error!

Upvotes: 2

Related Questions