I'm new to AngularJS and have seemingly a simple task. I want to reuse the AngluarJS LocalStorageModule on an empty page (no UI, execute once and redirect).
Here's how my attempt looks like:
<html>
<head>
<script src="../bower_components/angular/angular.js"></script>
<script src="../bower_components/angular-local-storage/dist/angular-local-storage.js"></script>
<script>
var myApp = angular.module('myApp', [ 'LocalStorageModule' ])
.factory(
function(localStorageService) {
localStorageService.set('username', 'some-user');
localStorageService.set('token', 'somevalue'));
window.location = location.protocol + '//' + location.hostname
+ (location.port ? ':' + location.port : '');
});
</script>
</head>
<body ng-app="myApp">You are being redirected
</body>
</html>
Unfortunately, the factory function is not being called. If I replace factory with the config the function is getting called but the localStorageServiceProvider doesn't expose set() method that I need.
The purpose of my exercise is to store value in the local browser storage for the real AngularJS application where the browser gets redirected to right after the above code gets executed, so that it can read and use the stored value.
.config()so the module injector can inject theLocalStorageModule. Afterwards you can use.run()to run the code that you need to run once. Also, use$locationfor redirection and such. Remember to inject$locationandLocalStorageFactoryinto the.run()function call. The.factory()function is used to create your own factories, not to reuse the existing modules/factories.var myApp = angular.module('myApp', ['LocalStorageModule']);for initial module injection. Afterwards you need to uselocalStorageServiceProviderwhen injecting the module inside functions, e.g..run(function(localStorageServiceProvider){/*code*/});