gpt4 book ai didi

angularjs - 从非 Angular 代码访问 Angular $cookies

转载 作者:行者123 更新时间:2023-12-01 10:39:26 28 4
gpt4 key购买 nike

我有一个 test 模块,将 cookie isTesting 设置为 true

app.controller('test_page',
['$scope', '$window', 'userService', 'flash', '$cookies',
function($scope, $window, userService, flash, $cookies) {
helper.initCommonScope($scope, $window, userService, flash)

$scope.refreshShownHidden = function() {
$scope.showTurnOffTest = $cookies.get('isTesting')
$scope.showTurnOnTest = ! $cookies.get('isTesting')
}

$scope.turnOnTest = function() {

$cookies.put('isTesting', true)
$scope.refreshShownHidden()
helper.turnOnTest()
}
$scope.turnOffTest = function() {
$cookies.put('isTesting', false)
$scope.refreshShownHidden()
helper.turnOffTest()
}

$scope.refreshShownHidden()

}])

在 helper.js 中,我有

exports.havePermission = function(access, resource, userService, entity) {
//Note: In debugging, we can grant client helper all access, and test robustness of server
if (angular.$cookies.isTesting)
return true
return permission.havePermission(access, resource, userService.isAuthenticated(), entity, userService.user)
}

但是 $cookies 不可用,因为 helper.js 不是任何 Angular 模块的一部分,因此没有可用的 DI。如何访问 isTesting 值?

我尝试使用 window.isTesting 代替,但当我刷新页面或转到其他页面时,它不会保留。所以cookie是更好的选择

最佳答案

您可以使用 Angular 的注入(inject)器来访问 Angular 应用程序外部的 Angular 模块和服务。

AngularJS 代码

angular.module('app', ['ngCookies']).
controller('ctrl', ['$cookies', function($cookies) {
$cookies.put('isTesting', true);
}]);

非 Angular 代码

helper = {
getCookies: function() {
// Create new injector for ngCookies module
var $injector = angular.injector(['ngCookies']);

// Inject $cookies to some function and invoke it
$injector.invoke(['$cookies', function($cookies) {
alert($cookies.get('isTesting'));
}]);
}
}

HTML

<html ng-app='app'>

<head>
<script data-require="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e3ece5f7eee3f0ace8f1c2b3acb6acb1" rel="noreferrer noopener nofollow">[email protected]</a>" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script>
<script data-require="<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d6b7b8b1a3bab7a4fbb5b9b9bdbfb3a5f8bca596e7f8e2f8e5" rel="noreferrer noopener nofollow">[email protected]</a>" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular-cookies.js"></script>
<script src="script.js"></script>
<script src="helper.js"></script>
</head>

<body ng-controller="ctrl">
<button onclick="helper.getCookies()">Click Me</button>
</body>

</html>

骗子:http://plnkr.co/edit/jur9A6d69ViiJqiFgopD?p=preview

关于angularjs - 从非 Angular 代码访问 Angular $cookies,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31490774/

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