2016-11-03 226 views
0

我試圖使用$篩選器來過濾從控制器中的JSON文件檢索的數據集。 這裏是在JSON文件中的數據:

[{ 
    "keyword": "key1", 
    "path": "path1" 
}, { 
    "keyword": "key2", 
    "path": "path2" 
}, { 
    "keyword": "key3", 
    "path": "path3" 
}, { 
    "keyword": "key4", 
    "path": "path4" 
}, { 
    "keyword": "key5", 
    "path": "path5" 
}] 

然後我得到的數據我的控制之內是這樣的:

$http.get('/sampleJson.txt').then(function (response) { 
    vm.resultSet=response.data; 
}); 

,然後我用$過濾器來過濾數據:

vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"}); 

最後我用ng-repeat在視圖中顯示數據:

<tbody> 
    <tr ng-repeat="result in vm.results"> 
    <td><a href="{{result.path}}">{{result.keyword}}</a></td> 
    <td>{{result.keyword}}</td> 
    </tr> 
</tbody> 

但結果變量是空的,沒有顯示出來。這似乎是非常基本的東西,但我無法弄清楚什麼是錯的? PS:當我在控制器聲明其它變量,如:

vm.message="Hello, Angular!" 

它在視圖中顯示出來。

回答

2

我寫使用$範圍的解決方案。該解決方案中的過濾器有效。我不知道爲什麼你使用虛擬機,但$ http服務工作asincronously,而行

vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"}); 

應該在的身體則()函數。

這裏是一個普拉克

https://plnkr.co/edit/gwx90oN0cf62JuUF5t2k?p=preview

1

$http是異步的,執行.thenvm.resultSet=response.data;)時(promise得到解決)後vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"});

試試這個,

$http.get('/sampleJson.txt').then(function (response) { 
    vm.resultSet=response.data; 
    vm.results=$filter('filter')(vm.resultSet, {keyword: "key1"}); 
}); 
+0

是的,你是對的。我之所以接受另一個答案是因爲發佈時間稍早。謝謝 – MehdiB