user2466886 user2466886 - 5 days ago 6
Javascript Question

How to pass results from POST request to another page in Ionic and Angular

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>

Answer

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;    
}
Comments