[英]AngularJS ng-repeat filter by specific ID from JSON
我似乎無法使這項工作。 我一直在嘗試按特定ID過濾JSON文件,然后使用ng-repeat進行迭代。
這是我嘗試過的
這是按鈕觸發器:
<a href="#/compare-details"><button class="viewDetails" ng-click="passID(11,02,00)" type="button">test button</button></a>
傳遞3個id參數后,它會進入我的控制器:
var newData;
angular.module('handsetExplorerModule')
.controller("compareDetailsController", ['$scope','compareDetailsService', function($scope, compareDetailsService) {
compareDetailsService.getHandsetList()
.then(
function(data){
$scope.passID = function(id1,id2,id3){
for(int i=0; i<data.phones.length; i++){
if(data.phones[i].id == id1 || data.phones[i].id == id2 || data.phones[i].id == id3){
newData += data.phones[i];
}
}
}
},
function(error){
//todo: handle error
}
);
$scope.phoneContent = newData;
}]);
JSON文件來自服務:
angular.module('handsetExplorerModule')
.factory('compareDetailsService', ['$http','$q', function($http, $q) {
var service = {
};
service.getHandsetList = function(){
var deferred = $q.defer();
$http.get("./data/compareJSON.json").then(function(response) {
deferred.resolve(response.data);
},
function(response){
deferred.reject("ERROR: Unable to get handsetList data");
}
);
return deferred.promise;
};
return service;
}]);
和我的重復
<div id="divContent">
<div>
<table id="Content" ng-repeat="x in phoneContent">
<tr>
<td class="one">
<table>
<tr>
<td><img class="contImage" ng-src="{{x.image}}" ng-alt="{{x.name}}" /></td>
<td class="textAlign">{{x.name}} <button class="viewDetails" ng-click="viewDetails(x.id)" type="button">VIEW DETAILS</button></td>
</table>
</td>
<td class="two">{{x.size}}</td>
<td class="one">{{x.storage}}</td>
<td class="two">{{x.camera}}</td>
<td class="one">{{x.battery}}</td>
<td class="two">{{x.network}}</td>
<td class="one">{{x.sim}}</td>
</tr>
</table>
</div>
</div>
請檢查重構一點點plunker: http ://plnkr.co/edit/paPSj8Dm4Z1RCbFw9FmS?p = preview
BTW, $ http服務由它自己是Promise,所以不需要使用$ q服務,只需返回$ http :
myApp.factory('compareDetailsService', ['$http', function($http) {
return {
getHandsetList: function(){
return $http.get("data.json");
}
};
}]);
有一個非常類似的教程,你應該看看: https : //docs.angularjs.org/tutorial/step_00
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.