0

I am trying to fetch string arrays from a json file and return the data back to a variable to form a word filer list, but "uncaught syntax error" kept showing can anyone help? Here comes my code:

    var filterWords = $http.get('word.json').success(function(res) {
      return angular.fromJson(res.data);
    });

    $scope.filterWord = function($string) {
         var wRegExp = new RegExp(filterWords.join("|"), "gi");
         return wRegExp.test($string);
    };

Thanks in advance!

4
  • There is no syntax error here. Some another part of your code causes an error. Commented Oct 22, 2015 at 7:21
  • plus, I am not sure that your code will work, you treat in the second function an async function as a sync function. Commented Oct 22, 2015 at 7:23
  • @Meir Does it mean that the data could be set to filterWords even after the filterWord() called? Commented Oct 22, 2015 at 7:36
  • It means that async calls usually set scope values (used by binding in the view) asynchronously Commented Oct 22, 2015 at 9:15

1 Answer 1

2

You don't have to do the angular.fromJson part, AngularJS does that for you. res.data will contain an object parsed from JSON if the result is JSON.

In the line var wRegExp = new RegExp(filterWords.join("|"), "gi"); you are not waiting for the result of filterWords, so you are calling join("|") on an HTTP promise. I'm not sure what the structure of your code is since I can only see the two lines you've shown, but perhaps you meant to set a variable in the success handler? Or have the success handler in the filterWord function?

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

3 Comments

I need the data in the json file and set them to filterWords for filterWord(). Maybe I should have the success handler in the filterWord function?
Then I would change the name of filterWords to filterWordsPromise and instead of returning something in the success handler I would do something like $scope.filterWord = res.data. Keep in mind that since the call is asynchronous, $scope.filterWord will be undefined for a while, then be set to the result.
Thanks a lot! So your idea is to define filterWord() as an asyn function while synchronized with $http.get right?

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.