2016-07-27 27 views
1

我有一個對象在下面的格式返回:遍歷中對象的項目,找到匹配和替換

[ 
    { 
     "category": "Coach", 
     "phrase_original": "Training {{the team}} to develop their match skills by ensuring they are comfortable with {{defence techniques}}", 
     "phrase_filter": "Training {{group}} to develop their {{attribute}} skills by ensuring they are comfortable with {{factor}}" 
    }, 
    { 
     "category": "Coach", 
     "phrase_original": "Assisting the {{fitness coach}} in strength and conditioning work to improve {{team performance}}", 
     "phrase_filter": "Assisting the {{person}} in strength and conditioning work to improve {{factor}}" 
    } 
] 

我想通過每個解析並替換:

  • {{group}}phrase_filter<span style="group*button">group</span>
  • phrase_filter
  • {{attribute}}<span style="attribute-button">group</span>
  • phrase_filterphrase_filter<span style="factor-button">group</span>
  • <span style="person-button">person</span>

什麼是解決這個問題的最好方法?

這是我的代碼到目前爲止,我不確定是否實現上述。我目前正在從API端點獲取數據,但不知道如何處理它。

CategoryService.getCategoryDetail($scope.categoryId).then(function(dataResponse) { 
    $scope.categoryDetail = dataResponse.data; 
    angular.forEach($scope.categoryDetail, function(e) { 
    // 1. find all the words in braces in phrase_filter 
    // 2. replace them with html markup so they are rendered in the view differently 
    // e.phrase_filter = ??? 
    }); 
}); 
+1

你應該添加angularjs作爲標記;)但你也可以在純JS –

回答

1

你可以嘗試這樣的事情:

var inputs = [ 
 
    { 
 
    "category": "Coach", 
 
    "phrase_original": "Training {{the team}} to develop their match skills by ensuring they are comfortable with {{defence techniques}}", 
 
    "phrase_filter": "Training {{group}} to develop their {{attribute}} skills by ensuring they are comfortable with {{factor}}" 
 
    }, 
 
    { 
 
    "category": "Coach", 
 
    "phrase_original": "Assisting the {{fitness coach}} in strength and conditioning work to improve {{team performance}}", 
 
    "phrase_filter": "Assisting the {{person}} in strength and conditioning work to improve {{factor}}" 
 
    } 
 
] 
 

 
var replacers = { 
 
    '{{group}}' : '<span style="group-button">group</span>', 
 
    '{{attribute}}' : '<span style="attribute-button">attribute</span>', 
 
    '{{factor}}' : '<span style="factor-button">factor</span>', 
 
    '{{person}}' : '<span style="person-button">person</span>' 
 
} 
 

 
// Loop through every objects 
 
inputs.forEach(function(input){ 
 
    Object.keys(replacers).forEach(function(key){ 
 
    // Replace every occurence of this key 
 
    input['phrase_filter'] = input['phrase_filter'].replace(new RegExp(key, 'g'), replacers[key]); 
 
    }) 
 
}) 
 

 
console.log(inputs);

但我不知道這是最好的解決方案regardind的事實,你有角的工作...你應該創建自定義指令或類似的東西,它會更有效;)希望它有幫助