Reputation: 1576
For any given route or state in an AngularJS application, I would like the option to use a mobile specific or desktop specific template depending on the user's device. I also want the user to be able to choose which version (desktop or mobile) regardless of the device they are on.
Specifically, I want a separate template because in many cases a separate template is far simpler than using responsive design.
Is there a simple way to accomplish this?
Here is what I would like to do, but I don't know how to make an 'isMobile' variable accessible to the templateUrl function using the angular-ui-router. Any help will be greatly appreciated.
angular
.module('app.items', [])
.config(config);
function config($stateProvider) {
//$window service not available in config block, so how can I set this variable?
var isMobile = $window.sessionStorage.getItem('isMobile');
$stateProvider
.state('itemsList', {
url: '/items',
templateUrl: function($stateParams) {
if (isMobile) { //How do I get this information (variable) in here?
return 'app/items/list.mobile.html';
}
else {
return 'app/items/list.desktop.html'
}
},
controller: 'ItemsListController'
});
}
Upvotes: 5
Views: 1190
Reputation: 1065
You can set that with a constant (assuming you can process the constant value before the app is bootstraped).
angular.module('app.items')
.constant('isMobile', window.sessionStorage.getItem('isMobile'));
.config(['$injector', function($injector) {
var $stateProvider = $injector.get('$stateProvider'),
isMobile = $injector.get('isMobile');
]});
EDIT TO ALLOW USER TO TOGGLE TEMPLATES
If you want to allow the user to make the selection, I would recommend creating a factory to get/set that value.
angular.module('app.items')
.factory('isMobile', [function() {
return {
get: function() { return $window.sessionStorage.getItem('isMobile'); },
set: function(bool) { $window.sessionStorage.setItem('isMobile', bool); }
};
}]);
Then in your $stateProvider
angular.module('app.items')
.config(['$stateProvider', function($stateProvider) {
$stateProvider
.state('itemsList', {
url: '/items',
templateUrl: ['$stateParams', 'isMobile', function($stateParams, isMobile) {
if (isMobile.get()) { return '/mobile/template.html'; }
else { return 'desktop/template.html'; }
}],
controller: 'ItemsListController'
});
}]);
The update will only happen on state change using this method, but you could feasibly perform some task on isMobile.set
that would force the change.
Upvotes: 0
Reputation: 5176
You may want to just by pass angular and use the native window.sessionStorage or if you want to let your user save a preference, window.localStorage. The $window service is essentially just a wrapper around this anyway.
Upvotes: 1