Sobakinet Sobakinet - 5 months ago 60
AngularJS Question

Angularjs convert string to object inside ng-repeat

i've got a string saved in my db

{"first_name":"Alex","last_name":"Hoffman"}


I'm loading it as part of object into scope and then go through it with ng-repeat. The other values in scope are just strings

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


But I want to use ng-repeat inside ng-repeat to get first and last name separate

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


And I get nothing. I think, the problem ist, that full name value is a string. Is it possible to convert it to object?

Answer

First off... I have no idea why that portion would be stored as a string... but I'm here to save you.

When you first get the data (I'm assuming via $http.get request)... before you store it to $scope.customers... let's do this:

$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

 }
})

Now NG-Repeat was designed to loop through arrays and not objects so your nested NG-Repeat is not necessary... your html should look like this:

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

This should fix your issue :)