我有一个以下列格式返回的对象:
[
{
"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>
{li} {{attribute}}
phrase_filter
<span style="attribute-button">group</span>
{li} {{factor}}
phrase_filter
<span style="factor-button">group</span>
{li} {{person}}
phrase_filter
<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 = ???
});
});
答案 0 :(得分: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);
&#13;
但是我不确定它是最好的解决方案,因为你使用角度...你应该创建自定义指令或类似的东西,它会更有效;)希望它有帮助< / p>