0

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.';
    };
};
Mistalis
  • 17,793
  • 13
  • 73
  • 97
Mzach
  • 21
  • 3
  • 1
    Debug your code, find where the problem is, add the information to your question. Then we can try to help you. But the error is pretty self-explanatory. – emerson.marini Jun 08 '16 at 08:41
  • 1
    [How to create a Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve) – emerson.marini Jun 08 '16 at 08:42
  • Tip : JS is asynchronous. http://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function – Jeremy Thille Jun 08 '16 at 08:42

2 Answers2

2

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!

Jeremy Thille
  • 26,047
  • 12
  • 43
  • 63
Abdel Raoof Olakara
  • 19,223
  • 11
  • 88
  • 133
  • Thanks guys for the solution. It's working as expected. Need to understand more on the $http concept. – Mzach Jun 08 '16 at 09:11
0

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

Fangming Cheng
  • 161
  • 1
  • 4
  • This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/14592312) – beryllium Dec 14 '16 at 14:58
  • 1
    @beryllium seems like an attempt to answer to me – Petter Friberg Dec 14 '16 at 15:00