Mohammad Amir
Mohammad Amir

Reputation: 178

If/else is not working in angularjs

enter image description hereIn this code if/else is not working. Am I making any mistake? data.success contains true/false. If I code like this if (data.success === true) then else block is working and if block is not working and vise versa.

$scope.verifyMobile = function () {
   var otp = {
      "otp": $scope.mobile.otp
   };
   $http({
      method: 'POST',
      url: 'verify_mobile',
      data: otp,
      headers: {
         'Content-Type': 'application/x-www-form-urlencoded'
      }
   }).success(function (data, status, headers, config) {
      if (data.success) {
          $scope.verified = true;
          $scope.sms_sent = false;
      } else {
          alert(data.message);
      }
   }).error(function (data, status, headers, config) {
   });
};

Upvotes: 0

Views: 666

Answers (3)

Ravi kumar Soni
Ravi kumar Soni

Reputation: 36

You should change the data.success and data.message to data.success[0] and data.message[0], because that are not boolean values you returning array in response that's why you have to take it in a array format. Try below code.

$scope.verifyMobile = function () {
        var otp = {
            "otp": $scope.mobile.otp
        };
        $http({
            method: 'POST',
            url: 'verify_mobile',
            data: otp,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        }).success(function (data, status, headers, config) {
            if (data.success[0]) {
                $scope.verified = true;
                $scope.sms_sent = false;
            } else {
                alert(data.message[0]);
            }
        }).error(function (data, status, headers, config) {
        });
};

Upvotes: 1

Arif
Arif

Reputation: 1643

Instead of .success() use .then().

Response will return an object you should check the response as below

$scope.httpRequest = function() {
  $http({
    method: 'GET',
    url: 'http://jsonplaceholder.typicode.com/posts/1',
  }).then(function(success) {
    if (success.data.userId === 1) {
      $scope.name = 'Jason Statham'
    } else {
      $scope.name = 'Cristiano Ronaldo'
    }
  }, function(error) {
    console.log(error)
  })
}

DEMO

Upvotes: 0

Surjeet Bhadauriya
Surjeet Bhadauriya

Reputation: 7156

This is because your data.success is not contains boolean value. So before your if-else block try to print type of data.success

console.log(typeof data.success);

And see is it boolean if not then just resolve it.

Upvotes: 0

Related Questions