Amit Phartiyal Amit Phartiyal - 27 days ago 9
AngularJS Question

Getting details from the json file using AngularJS using search input

My Goal:

I want to search for the member details on input of the member id.


What i have don't till now?:

My view is ready.I have create a service named myService which use $http
service to grab data from the members.json file.


My Problem?

Instead getting the details of the particular id searched, I am getting
names of all members


What is want to ask?

Who to get only the details of the searched member using his id.

This is my view
[1]: https://i.stack.imgur.com/PQ0BP.jpg
This is my code
[1]: https://i.stack.imgur.com/Q9tZp.jpg
This is my json file
{
"member":[
{ "Id":"1",
"Name":"Amit Singh",
"Dateofjoin":"21-03-2003",
"Number":"934234334"
},{
"Id":"2",
"Name":"Mohamad Aamir",
"Dateofjoin":"21-03-2012",
"Number":"934343434"
}
]
}




<body ng-app="myApp" ng-controller="ctrl">
<div>
<form class="form-horizontal">
<h2>Search for members.</h2>
<input type="text" name="" class='form-control' placeholder="Member ID"
ng-model="searchId"/><br>
<button class="btn btn-primary" ng-click="doSearch()">Search</button>
</form>
<div>
<p ng-repeat="x in data">
{{x.Name}}
</p>
</div>


</div>
</body>
<script type="text/javascript">
var app = angular.module("myApp",[]);

app.controller('ctrl',
['$scope','myService','$log',function($scope,myService,$log){
$scope.doSearch = function(){
myService.getData($scope.searchId).then(function(data){
$scope.data = data;
$log.info($scope.data);
});
};
}])
app.service('myService', ['$http','$log', function($http,$log){
this.getData = function(memberId){
return $http({
url:"members.json",
method:"GET",
dataType: 'json',
contentType: "application/json"

}).then(function(response){
var myData = response.data.member;
return(myData);
},function(response){
throw response;
});
}
}]);

</script>

Answer Source

Sorry I misunderstood the question here's the right answer:

app.service('myService', ['$http','$log', function($http,$log){
        this.getData = function(memberId){
            return $http({
                url:"members.json",
                method:"GET",
                dataType: 'json',
                contentType: "application/json"

            }).then(function(response){
                var myData = response.data.member.filter(member=>member.Id==memberId)[0];
                return(myData);
            },function(response){
                throw response;
            });
        }
    }]);