0

I have an if-else block that parses user input before making a http.get() to the server. However, the if-else keeps on being skipped over. I tried rearranging my code to force it to complete the if-else before calling get(), but nothing seems to work. I'm also using AngularJS.

//controller
function search($scope, $http, $location) 
{
    function parse(item)
    {
      if(item.match(/str1/g))
      {
        item = item.replace(/str1/g, 'one');
      }

      else if(item.match(/str2/g))
      {
        item = item.replace(/str2/g, 'two');
      }

      else if(item.match(/str3/g))
      {
        item = item.replace(/str3/g, 'three');
      }

      //ad infinitum
      return item;
    }

    $http.get('/search='+ parse($location.search().query.toLowerCase()))
         .success(function(data) {
            $scope.count = data.length;
            $scope.items = data;
            $scope.exists = data.length > 0;
         })
         .error(function(err) {

         });
}
1
  • I think you need to learn about return statements. Commented Jun 9, 2015 at 18:40

1 Answer 1

1

You're not returning item in your parse() function. Your parse() function is being treated as a string but there's no return value.

At the end of your function there should be a return, like so:

function parse(item)
{
  if(item.match(/str1/g))
  {
    item = item.replace(/str1/g, 'one');
  }

  else if(item.match(/str2/g))
  {
    item = item.replace(/str2/g, 'two');
  }

  else if(item.match(/str3/g))
  {
    item = item.replace(/str3/g, 'three');
  }

  //ad infinitum

  return item;

}

Read up on return Statements here: http://www.w3schools.com/jsref/jsref_return.asp

Another way to accomplish what you're trying to do is simply not creating a local parse() function and just doing the string handling directly in the search() scope:

function search($scope, $http, $location) 
{
      var item = $location.search().query.toLowerCase();

      if(item.match(/str1/g))
      {
        item = item.replace(/str1/g, 'one');
      }

      else if(item.match(/str2/g))
      {
        item = item.replace(/str2/g, 'two');
      }

      else if(item.match(/str3/g))
      {
        item = item.replace(/str3/g, 'three');
      }

      //ad infinitum

    $http.get('/search='+ item)
         .success(function(data) {
            $scope.count = data.length;
            $scope.items = data;
            $scope.exists = data.length > 0;
         })
         .error(function(err) {

         });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.