2015-09-28 37 views
2

對象裏面我已經得到了保存在我的數據庫Angularjs字符串轉換爲NG-重複

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

我加載它作爲對象爲範圍的一部分,然後通過它與NG-重複的字符串。在範圍內的其他值都只是字符串

{"id":"38","fullname":"{\"first_name\":\"Alex\",\"last_name\":\"Hoffman\"}","email":"[email protected]","photo":"img.png"} 

但我想用NG重複內NG重複獲得的姓和名分開

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

,我什麼也沒得到。我認爲,問題在於,全名值是一個字符串。是否有可能將其轉換爲對象?

回答

6

首先...我不知道爲什麼那部分會被存儲爲一個字符串......但我來救你。

當你第一次得到的數據(我通過$ 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-重複是沒有必要的......你的HTML應該是這樣的:

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

這應該可以解決您的問題:)

+0

是的,這工作...但我認爲在PDO querry或SQL中有一些問題...我不明白,爲什麼我把它作爲一個字符串。將嘗試解決它。如果沒有 - 堅持你的建議 – Sobakinet

+0

很高興能幫到你:D –

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> 
+0

我不知道它是否是一個字符串,但它不適用於ng-repeat,所以我認爲,這是一個字符串。我是否必須迭代整個範圍對象來轉換每個字符串值?不能在模板中完成嗎? – Sobakinet

+0

@Sobakinet - 我會說第一步是發現這是否是一個實際的字符串 - 如果它不是* - 你需要使用正確的'ngRepeat'語法 - 如果是,那麼你可以*創建一個'過濾器「將其轉換 - 但爲什麼不在客戶端獲取之前通過服務器轉換呢? – tymeJV

+0

是我的問題中最後一個代碼片段中的ng-repeat語法不正確? – Sobakinet

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 
    }; 
    } 
]); 
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; 
    } 

});