简体   繁体   English

在angularjs控制器中从json获取字符串数组

[英]Fetch string arrays from json in angularjs controller

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? 我正在尝试从json文件中提取字符串数组,并将数据返回到变量以形成单词过滤器列表,但是“未捕获的语法错误”一直显示有人可以帮助吗? 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! 提前致谢!

You don't have to do the angular.fromJson part, AngularJS does that for you. 您不必做angular.fromJson部分,AngularJS会为您完成。 res.data will contain an object parsed from JSON if the result is JSON. 如果结果为JSON,则res.data将包含从JSON解析的对象。

In the line var wRegExp = new RegExp(filterWords.join("|"), "gi"); 在此行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. 您没有在等待filterWords的结果,因此您正在通过HTTP filterWords调用join("|") 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? 我不确定您的代码结构是什么,因为我只能看到您显示的两行,但是也许您想在success处理程序中设置一个变量? Or have the success handler in the filterWord function? 还是在filterWord函数中有success处理程序?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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