I have referenced a lot of questions in stack over flow for this topic. But none of them seems to work for me.
I have two html pages: AddUser.html and ListUser.html. Both pages have the same ng-app="myApp" directive, but two different controllers.
AddUser.html
ng-app="myApp" ng-controller="userCtrl"
ListUser.html
ng-app="myApp" ng-controller="listCtrl"
I need to pass the data added from Adduser page to Listuser page. For this i have written a service
app.js
var ang = angular.module('myApp', ['ngRoute']);
ang.config(function ($routeProvider) {
$routeProvider
.when('/Add_Users', {
templateUrl: 'Add_Users.html',
controller: 'userCtrl'
})
.when('/List_Users', {
templateUrl: 'List_Users.html',
controller: 'listCtrl'
})
.otherwise({
redirectTo: '/Add_Users'
});
});
service.js
ang.service('userService', function () {
var userList = [];
var addUser = function (newObj) {
console.log("called addUser");
userList.push(newObj);
console.log("userList AFTER ADD::" + userList);
};
var getUsers = function () {
console.log("called getUsers" + userList + " >>");
return userList;
};
return {
addUser: addUser,
getUsers: getUsers
};
});
In controller i am calling the service methods. like below
ang.controller('userCtrl', function ($scope,userService) {
userService.addUser($scope.user_details);
});
and retrieving it in the next controller
ang.controller( "listCtrl",function($scope,userService){
$scope.userlist = userService.getUsers();
});
But in the second page, the object is empty. Tried a number of solutions, but none of them seems to work.
Is this because of the ng-app directive in the second page,causing the service to be re-initialzed?