首页 > 解决方案 > 与打印时的静态数据相比,在控制台上打印的动态数据显示不同

问题描述

我正在将带有逗号分隔值的字符串从弹簧控制器返回到角度控制器,如下所示。

app.controller('myListController', ['$scope', function ($scope) {

//get data dynamically , logic..
$scope.myList = response;
console.log("$scope.myList  " + $scope.myList); // "one,two","three","four","five,eight,nine"

//here i want to print as one,two,three,four,five,eight,nine 

//convert string to array with comma separated values
var array_list = JSON.parse($scope.myList);
   console.log("array_list :: " + array_list);
}]);

上面的代码抛出错误

angular.min.js?dummy=0.6014859345541128:119 SyntaxError: Unexpected token , in JSON at position 15
    at JSON.parse (<anonymous>)

相同的代码,当替换为静态代码时,它按预期工作。例子:

   $scope.myList = ["one,two","three","four","five,eight,nine"];

   console.log("$scope.myList static content:: " +   $scope.myList); //one,two,three,four,five,eight,nine

上面的任何输入?

标签: javascriptangularjshtml-parsing

解决方案


正如我在您的 JSON.stringify 结果中看到的,您的响应字符串必须是这个值:

'"one,two","three","four","five,eight,nine"'

如果是,您可以使用简单的正则表达式来获得您想要的结果:

var result = $scope.myList.replace(/"/g, ""); //"one,two,three,four,five,eight,nine"

如果这不起作用,请分享您的 $scope.myList 的确切值


推荐阅读