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.sstatic.net/PQ0BP.jpg
This is my code
[1]: https://i.sstatic.net/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>
response.data.member, which is the array of all members. It doesn't do anything with thememberIdthat is passed as argument. So... why do you think this service should return only one member, idendified by the memberId? Why don't you change your code to look for the member identified by memberId, and returns that instead of the whole array? You need a loop. Or a call to Array.filter().