AngularJS在ng-repeat中将字符串转换为对象

3
我在数据库中保存了一个字符串。
{"first_name":"Alex","last_name":"Hoffman"}

我将其作为对象的一部分加载到作用域中,然后使用ng-repeat进行遍历。作用域中的其他值仅为字符串。

{"id":"38","fullname":"{\"first_name\":\"Alex\",\"last_name\":\"Hoffman\"}","email":"alex@mail","photo":"img.png"}

但是我想在ng-repeat内部再使用ng-repeat来分别获取名字和姓氏

<div ng-repeat="customer in customers">    
    <div class="user-info" ng-repeat="name in customer.fullname">
       {{ name.first_name }} {{ name.last_name }}
    </div>
</div>

我什么也没得到。我认为问题在于全名值是一个字符串。是否可能将其转换为对象?

4个回答

7

首先...我不知道为什么这部分会被存储为字符串...但我来帮你解决。

当你第一次获取数据(我假设是通过 $http.get 请求)...在将其存储到 $scope.customers 之前...让我们这样做:

$http.get("Whereever/You/Get/Data.php").success(function(response){
//This is where you will run your for loop
  for (var i = 0, len = response.length; i < len; i++){
    response[i].fullname = JSON.parse(response[i].fullname)
    //This will convert the strings into objects before Ng-Repeat Runs
  //Now we will set customers = to response
   $scope.customers = response

 }
})

现在NG-Repeat被设计用于循环遍历数组而不是对象,所以你的嵌套NG-Repeat是不必要的...你的html应该像这样:
<div ng-repeat="customer in customers">    
<div class="user-info">
   {{ customer.fullname.first_name }} {{ customer.fullname.last_name }}
</div>

这应该会解决你的问题 :)

没错,这可以运行...但我认为PDO查询或SQL存在一些问题...我不明白为什么会得到一个字符串。我会尝试解决它。如果不行-我会遵循你的建议。 - Kotanet

2

您需要将字符串值转换为对象(为什么是字符串,我不知道)。

.fullname = JSON.parse(data.fullname); //replace data.fullname with actual object

然后使用对象ngRepeat语法((k, v) in obj):

<div class="user-info" ng-repeat="(nameType, name) in customer.fullname">
    {{nameType}} : {{name}}
</div>

我不确定它是否为字符串,但它无法与ng-repeat一起使用,因此我认为它是一个字符串。我是否必须遍历整个作用域对象以转换每个字符串值?难道不能在模板中完成吗? - Kotanet
@Sobakinet - 我认为第一步是找出它是否是一个实际的字符串 - 如果不是 - 你需要使用正确的 ngRepeat 语法 - 如果是,那么你可以创建一个 filter 来转换它 - 但为什么不在客户端获取之前通过服务器将其转换呢? - tymeJV
在我提问中的最后一个代码片段中,ng-repeat语法是否不正确? - Kotanet
@Sobakinet -- 这是数组的语法 [1,2,3] - 对于对象,它是不同的 {name:"Justin", number:3} - (k, v) in obj - tymeJV

1

我曾经遇到过同样的问题,但是通过自定义过滤器解决了这个问题...

JSON:

.........
"FARE_CLASS": "[{\"TYPE\":\"Economy\",\"CL\":\"S \"},{\"TYPE\":\"Economy\",\"CL\":\"X \"}]",
.........

UI:
<div class="col-sm-4" ng-repeat="cls in  f.FARE_CLASS | s2o">
   <label>
       <input type="radio"  ng-click="selectedClass(cls.CL)" name="group-class" value={{cls.CL}}/><div>{{cls.CL}}</div>
   </label>
</div>

自定义过滤器:
app.filter("s2o",function () {
    return function (cls) {
        var j = JSON.parse(cls);
        //console.log(j);
        return j;
    }

}); 

1
我建议您使用类似过滤器的东西: <div class="user-info"... ng-bind="customer | customerName">... 过滤器将会是这样:
angular.module('myModule').filter('customerName', [function () {
    'use strict';

    return function (customer) {
      // JSON.parse, compute name, foreach strings and return the final string
    };
  }
]);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接