由Fissio回答
我正在尝试在Angular中制作一个简单的搜索功能。当用户在输入框中输入内容时,我希望能够搜索我的JSON中的所有“标题”,如果某个词与输入匹配,则带回与匹配相关的所有对象。
工厂
我首先创建了一个工厂,使用Promise从JSON中检索数据。
.factory('podcastData', function($http) {
var podcastData = {
async: function() {
var promise = $http.get('http://radio-sante-animale.fr/podcast-data.php').then(function(response) {
return response.data.categories;
})
return promise;
}
};
return podcastData;
})
然后在我的控制器中,我尝试在控制器中编写一个搜索程序。 目前为止,我已经成功使用for循环,获取了数组的长度,然后获取了数组中的所有“播客”,最后成功将所有匹配输入值的值获取到。
控制器
更新
$scope.findValue = function(enteredValue) {
console.log(enteredValue);
var filtered = [];
podcastData.async().then(function(data) {
for (i = 0; i < data.length; i++) {
angular.forEach(data[i].podcasts, function(podcasts, key) {
var foundPodcasts = _.filter(podcasts, function(podcast) {
return podcasts.title.toLowerCase().indexOf(enteredValue) >= 0
});
if (typeof foundPodcasts !== 'undefined') {
filtered.concat(foundPodcasts);
console.log(foundPodcasts);
};
});
}
});
}
我已更新控制器,现在我可以返回所有与搜索输入匹配的对象,但是当我使用console.log打印 foundPodcasts 时,我的响应如下图所示。这很好!然而,数组之间是空的,并且我无法使用NG-REPEAT,因为没有值可供我获取。