gpt4 book ai didi

javascript - 调用 Angularjs 模块一次

转载 作者:行者123 更新时间:2023-12-03 06:45:55 25 4
gpt4 key购买 nike

我是 AngularJS 的新手,似乎有一个简单的任务。我想重用AngluarJS LocalStorageModule在空白页面上(无 UI,执行一次并重定向)。

这是我的尝试:

<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>

不幸的是,工厂函数没有被调用。如果我用配置替换工厂,则会调用该函数,但 localStorageServiceProvider 不会公开我需要的 set() 方法。

我练习的目的是在真正的 AngularJS 应用程序的本地浏览器存储中存储值,其中浏览器在执行上述代码后立即重定向到,以便它可以读取和使用存储的值。

最佳答案

您需要注入(inject)模块,配置它,然后使用它。

//load and config the modules
var myApp = angular.module('myApp', [ 'LocalStorageModule' ]);
myApp.config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setPrefix('samePrefixAsTheTargetApp');
});
//this function is called only once
myApp.run(function(localStorageService){
localStorageService.set('username', 'some-user');
localStorageService.set('token', 'somevalue'));
window.location = location.protocol + '//' + location.hostname
+ (location.port ? ':' + location.port : '');
})

关于javascript - 调用 Angularjs 模块一次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37737614/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com