简体   繁体   中英

Getting TypeError using Angular.js and PHP

I am getting the following error using angular.js and PHP.

Error:

TypeError: $scope.classData.unshift is not a function
    at successCallback (adminResourceClassController.js:55)
    at angularjs.js:118
    at n.$eval (angularjs.js:132)
    at n.$digest (angularjs.js:129)
    at n.$apply (angularjs.js:133)
    at g (angularjs.js:87)
    at K (angularjs.js:91)
    at XMLHttpRequest.z.onload (angularjs.js:92)

I am explaining my code below.

if($scope.buttonName=="Add"){
            if($scope.colg_name.value=='' || $scope.colg_name.value==null){
                alert('select college name');
                classField.borderColor('colg_name');
            }else if($scope.subject==null || $scope.subject==''){
                alert('Subject Type field could not be blank...');
                classField.borderColor('resourcesub');
            }else if($scope.period=='' || $scope.period==null){
                alert('Please select the no of period...');
                classField.borderColor('resourceperiod');
            }else{
                var userdata={'colg_name':$scope.colg_name.value,'sub_type':$scope.subject,'period':$scope.period};
                $http({
                    method:'POST',
                    url:"php/resource/addClassData.php",
                    data:userdata,
                    headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
                }).then(function successCallback(response){
                    alert(response.data['msg']);
                    $scope.colg_name.value='';
                    $scope.subject=null;

                    $scope.classData.unshift(response.data);
                },function errorCallback(response) {
                    alert(response.data['msg']);
                    if($scope.subject==response.data.type){
                        classField.borderColor('resourcesub');
                    }else{
                    $state.go('dashboard.res.class',{}, { reload: true });
                    }
                });
            }
        }

I am getting this error when $scope.classData is null.I put the condition of if statement(eg-if($scope.classData==null)) but it can not check anything.Please help me to resolve this error.

The proper way to check if $scope.classData exists is with

if ('undefined' !== typeof $scope.classData) {}

or

if (angular.isDefined($scope.classData)) {}

I'm not sure what the rest of your code looks like but inside your controller you should define $scope.classData as an empty array, so you can push or unshift new items into it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM