每次尝试查找匹配项并替换单个项目中的文本时,我都会收到以下错误消息:TypeError: $scope.phraseDetail.forEach is not a function
。
以下代码在iterating over multiple items in an object时工作正常,即API输出如下:
/ API /短语/
[
{
"id": "f40e0e47-6457-463b-a5f9-9dc97bd2d0ce",
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}"
},
{
"id": "66314a72-07ae-445c-97c0-4f659387bbb2",
"phrase": "Assisting {{person}} in strength and conditioning work to improve {{factor}}"
}
]
但是,当只返回一个项目时,它不起作用,即如下:
API /短语/ f40e0e47-6457-463b-a5f9-9dc97bd2d0ce /
{
"id": "f40e0e47-6457-463b-a5f9-9dc97bd2d0ce",
"phrase": "Training {{group}} to develop their {{attribute}} by ensuring they are comfortable with {{factor}}"
}
我该如何解决这个问题?我在下面提供了我的代码:
phrase-detail.html (注意:bind-html-compile是我从https://github.com/incuna/angular-bind-html-compile抓取的指令)
<div class="list">
<div class="item item-text-wrap item-line-height" bind-html-compile="phraseDetail.phrase"></div>
</div>
controllers.js
function PhraseDetailCtrl($scope, $stateParams, PhrasesService, FilterService, $ionicLoading, $timeout) {
$ionicLoading.show({
content: 'Loading',
animation: 'fade-in',
showBackdrop: true,
maxWidth: 200,
showDelay: 0
});
$timeout(function () {
$ionicLoading.hide();
$scope.dataLoaded = true;
$scope.phraseId = $stateParams.phraseId;
PhrasesService.getPhrasesDetail($scope.phraseId).then(function(dataResponse) {
$scope.phraseDetail = dataResponse.data;
var replacers = FilterService.getItemFilter();
$scope.phraseDetail.forEach(function(e){
Object.keys(replacers).forEach(function(key){
e['phrase'] = e['phrase'].replace(new RegExp(key, 'g'), replacers[key]);
})
})
})
}, 1000)
$scope.$watch('toggle', function(){
$scope.toggleText = $scope.toggle ? 'Toggle!' : 'some text';
})
}
services.js
/**
*
*/
function PhrasesService($http) {
this.getPhrasesDetail = function (phraseId) {
return $http({
method: 'GET',
url: server + '/api/phrases/' + phraseId,
});
}
}
/**
*
*/
function FilterService() {
this.getItemFilter = function () {
var replacers = {
'{{group}}' : '<div class="button button-small button-outline button-positive button-side-padding">group</div>',
'{{attribute}}' : '<div class="button button-small button-outline button-assertive button-side-padding">attribute</div>',
'{{factor}}' : '<div class="button button-small button-outline button-assertive button-side-padding">factor</div>',
'{{person}}' : '<div class="button button-small button-outline button-positive button-side-padding">person</div>'
}
return replacers;
}
}