I have a list. What I want is when I click on one of the item of List a new page should open where the data related to only that listItem is displayed. Right now I am using anchor tag and .config to pass data like this:
<ion-item ng-repeat="field in fields">
<a href="#detail/{{field.firstName}}/{{field.personNo}}/{{field.street}}/{{field.city}}/{{field.postcode}}" id="a-item"> <div style="width:100%;height:100%" >
{{field.firstName}}<br>
{{field.personNo}} </div></a>
</ion-item>
And
.config(['$routeProvider',
function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/mainpage.html'
}).
when('/detail/:name/:no/:street/:city/:postcode', {
templateUrl: 'templates/details.html',
controller: 'detailctrl'
})
}])
I don't think this is an effective way to pass data. Although I know about .service but I can't figure out a way to pass data specific to the item clicked. Please suggest a better way. Thanks
What you're looking at is the classic master detail pattern that you indeed would want to use a service (or factory) for.
First change I'll make to your code is giving the main route a controller, as well as for the details route only passing in the personNo.
.config(['$routeProvider',function($routeProvider) {
$routeProvider.
when('/', {
templateUrl: 'templates/mainpage.html',
controller: 'mainctrl'
}).
when('/detail/:no', {
templateUrl: 'templates/details.html',
controller: 'detailctrl'
})
}])
Next, let's set up a "PeopleService" via a factory with two methods. One, is the GetPeople method which gets all the people in an array and resolves a promise via $http before storing it in a private variable. The GetPerson method looks up a person by personNo in that private variable.
.factory('PeopleService',['$http',function($http){
var people = [];
return {
GetPeople: function(){
$http.get("path/to/resource").then(function(response){
people = response;
return response;
});
},
GetPerson: function(personNo){
for(i=0;i<people.length;i++){
if(people[i].personNo == personNo){
return people[i];
}
}
}
}
}]);
Next, in our mainctrl we will want to call that GetPeople function.
.controller("mainctrl",['PeopleService',function(PeopleService){
PeopleService.GetPeople().then(function(people){
$scope.people = people;
});
}]);
Finally, in our detailsctrl, we will get the personNo from the $routeParams and use it to call the GetPerson method from our service.
.controller("detailctrl",['$routeParams','PeopleService',function($routeParams,PeopleService){
var personNo = $routeParams.no;
$scope.person = PeopleService.GetPerson(personNo);
}]);