The task is to select a device in a select box and display the properties related to name i.e. Name, type, device_family etc. on the other page.
The problem that I am getting is that the data gets set in the 1st controller. That's fine but it doesn't go to the next page which uses DeviceController2. The alert of DeviceController2 does not show any value in it. I just have to send the device to next page.
For this, my 1st controller is
App.controller('DeviceController', function($scope,$http,commonDeviceService) {
var self = this;
self.show = function(device){
commonDeviceService.set(device);
alert("Device selected is "+device);
window.open('url to next page');
};
});
commonDeviceService is my common service for the controllers.
2nd controller is
App.controller('DeviceController2', function($scope,$http,commonDeviceService) {
$scope.device = commonDeviceService.get();
alert($scope.device);
});
And the commonDeviceService is
App.factory('commonDeviceService', function() {
var shareddata='';
function set(data) {
shareddata = data;
alert("shared data in set call is "+shareddata);
}
function get() {
alert("shared data in get call is "+ shareddata);
return shareddata;
}
return {
set: set,
get: get
};
});
Often we need to keep a client session state in our angularjs application so it would survive page refresh and navigations within the application. for such cases you may use $window.sessionStorage
Controller1:
App.controller('DeviceController', function($scope,$http,$window) {
var self = this;
self.show = function(device){
$window.sessionStorage.device = device;
alert("Device selected is "+device);
window.open('url to next page');
};
});
Controller2:
App.controller('DeviceController2', function($scope,$http,$window) {
$scope.device = $window.sessionStorage.device;
alert($scope.device);
});
this will serve your purpose of data sharing between controllers but one should keep in mind that its storage capacity is limited to 5MB. Also if you open a new tab to the exact same URL it will be a new sessionStorage object. Reference: $window.sessionStorage vs $cookieStore
I have removed the code for angular factory assuming that it's only purpose was for this data sharing which has now been fulfilled by session storage.