Reputation: 205
I'm using ionic to build a mobile app and I'm implementing very lightweight authentication (no security) into the app. Basically when a users hits the login button after submitting their email and password, their information is checked against a database using a POST request. Now my question is, once I have confirmed that the user's information is in the database, I'd like to pass that response object from the POST to a profile page that can then show the user's profile information. How can I pass information (the response object) from one controller to the another page so it can then be displayed on screen? Code below:
app.js
//Login view
.state('signin', {
url: '/signin',
templateUrl: 'templates/signin.html',
controller: 'LoginCtrl'
})
// Profile view:
.state('tab.profile', {
url: '/profile',
views: {
'tab-profile': {
templateUrl: 'templates/tab-profile.html'
controller: 'ProfileCtrl'
}
}
})
controllers.js:
$http.post(url, obj)
.success(function (res, status, headers, config) {
if (res == null){
console.log("bad login");
}
else{
// $scope.response = res;
console.log(res);
console.log("post successful");
$state.go('tab.profile',{response:res});
}
});
tab-profile.html
<ion-view view-title="Profile">
<ion-content>
<ion-list>
<ion-item >{{response.name}}</ion-item>
</ion-list>
</ion-content>
</ion-view>
Upvotes: 3
Views: 977
Reputation: 38189
You can create a service
which will store data to be passed to other controllers
.
Let me show an example:
var yourApp = angular.module('fooApp', []);
yourApp.factory('yourFactory', function() {
var items = [];
var storeService = {};
storeService.addItem = function(item) {
items.push(item);
};
storeService.removeItem = function(item) {
var index = items.indexOf(item);
items.splice(index, 1);
};
storeService.items = function() {
return items;
};
return storeService;
});
function MyCtrl($scope, yourFactory) {
$scope.newItem = {};
$scope.yourFactory = yourFactory;
}
Upvotes: 2
Reputation: 147
You can define params in the definiton of a route. Look at the docu (https://github.com/angular-ui/ui-router/wiki/URL-Routing) of the ui-router module to see the right syntax.
In order to pass more complex object between two controllers i would use a service. Xou can set the data in the service after the POST is resolved and after the state change read it in the other controller. Read this link to see examples Passing data between controllers in Angular JS?. Hope this helps :)
Upvotes: 1