We always have basic requirement to pass object from one page to another in our application in Ionic 1. To do so follow the below steps:
Step 1: Create an application using the command:
ionic start passobject blank
Step 2: Define states in app.js file . In this demo application 2 states are created.
myapp.config(function ($stateProvider, $urlRouterProvider) {
$stateProvider
.state('mainPage', {
url: '/mainPage',
templateUrl: 'views/main.html',
controller: 'namesCtrl'
})
.state('listPage', {
url: '/listPage',
templateUrl: 'views/list.html',
controller: 'namesCtrl',
params: {objectName: null} ////////////params additional parameter added
})
$urlRouterProvider.otherwise('/mainPage'); ////////////to make Home Screen
});
In listPage state an additional parameter is added params which will handle the object and initialized as null.
Step 3: Make controller.js file in js folder of www in application with the code:
myapp.controller('namesCtrl', function ($scope, $state, $stateParams) {
$scope.details = $stateParams.objectName;
$scope.chats = [
{ name: 'Jani', country: 'Norway', url: '/img/ionic.png' },
{ name: 'Hege', country: 'Sweden', url: '/img/ionic.png' },
{ name: 'Kai', country: 'Denmark', url: '/img/ionic.png' }
];
$scope.chatDetail = function (data) {
$state.go('listPage', { objectName: data });
}
});
In chatDetail function data is passed as object and inside this function $state.go is used to change state with which we pass object as param.
Step 4: Now make the html pages for main page and list page.
main.html
<ion-view view-title="Chats">
<ion-content>
<ion-list>
<ion-item ng-repeat="chat in chats">
<a ng-click="chatDetail(chat)">
<h2>{{chat.name}}</h2>
</a>
</ion-item>
</ion-list>
</ion-content>
</ion-view>
list.html
<ion-view view-title="{{details.name}}">
<ion-content class="padding">
<h2>{{details.name}}</h2>
<img ng-src="{{details.url}}" style="width: 64px; height: 64px">
<p> {{details.country}}</p>
</ion-content>
</ion-view>
Here the details contains the selected item detail from the mainPage state .
Leave a comment