2016-07-27 70 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的事实,你有角的工作...你应该创建自定义指令或类似的东西,它会更有效;)希望它有帮助