gpt4 book ai didi

javascript - AngularJS ng-repeat 按 JSON 中的特定 ID 进行过滤

转载 作者:行者123 更新时间:2023-11-28 05:27:31 25 4
gpt4 key购买 nike

我似乎无法完成这项工作。我一直在尝试按特定 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参数后,它会转到我的 Controller :

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;
}]);

和我的 ng-repeat

<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

顺便说一句,$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

关于javascript - AngularJS ng-repeat 按 JSON 中的特定 ID 进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40010429/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com