[英]Using Cookie value from one ng-app in another ng-app in AngularJS
I know that it isn't good practice to have multiple ng-apps in a project but my project is divided into segments that aren't generally related to each other, plus I am left with more or less no other option. 我知道在一个项目中拥有多个ng-apps不是一个好习惯,但是我的项目被划分为通常互不相关的部分,再加上我几乎没有其他选择。
My problem is the persistence of ng-cookie
amidst two separate Javascript files. 我的问题是在两个单独的Javascript文件中
ng-cookie
的持久性。 Let's say I have dashboard1.html
that is linked to controller1.js
and dashboard2.html
linked to controller2.js
. 比方说,我有
dashboard1.html
链接到controller1.js
和dashboard2.html
挂controller2.js
。
Now, I want to access the cookie value of controller 1 in controller 2. When I try to do this the result says undefined and that means I cannot access the cookie value set by another Javascript file. 现在,我想访问控制器2中控制器1的cookie值。尝试执行此操作时,结果显示为undefined,这意味着我无法访问另一个Javascript文件设置的cookie值。
Please advise me how to solve this issue. 请告诉我如何解决此问题。
NOTE : Javascript files have respective ng-app defined and controller for each application. 注意:Javascript文件为每个应用程序定义了各自的ng-app和控制器。
This is Controller and ng-app
part of one module. 这是一个模块的Controller和
ng-app
一部分。
var app = angular.module('mainpageapp', ['ngRoute','ngCookies']);
app.controller('ctrlmainpage', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies) {
console.log("Csadad");
$cookies.myFavorite = 'TestCookie';
var favoriteCookie = $cookies.myFavorite;
console.log("Cookie" + favoriteCookie);
Now in this ng-app's controller I am setting a cookie, it works properly and I do get expected response on console. 现在,在此ng-app的控制器中,我正在设置一个cookie,它可以正常工作,并且确实在控制台上得到了预期的响应。 This is in file controller1.js
这在文件controller1.js中
Now I am trying to access the same cookie in controller2.js that is all together bound by different ng-app. 现在,我尝试访问controller2.js中的同一cookie,该cookie都由不同的ng-app绑定在一起。
var app = angular.module('myApp', ['ngRoute', 'smart-table', 'ngCookies']);
var id = 'hasdh';
app.controller('dashmerctrl', ['$scope', '$timeout','$http', '$route', '$routeParams', '$location', '$rootScope', '$cookies', function ($scope, $timeout, $http, $route, $routeParams, $location, $rootScope, $cookies)
{
var favoriteCookie1 = $cookies.myFavorite;
console.log("Cookie1" + favoriteCookie1);
Her I get undefined as output. 她我未定义为输出。
I want to access that same cookie in this file. 我想访问此文件中的同一cookie。
if you wish to share data across tabs or domains you can give zendesk's "cross-storage" a try, just implemented it with AngularJS and it works like a charm. 如果您希望跨选项卡或域共享数据,则可以尝试zendesk的“跨存储”,只需使用AngularJS进行实现即可,它就像一个魅力。
it utilizes window.postMessage() technique to achieve this behavior. 它利用window.postMessage()技术来实现此行为。
link: zendesk/cross-storage 链接: zendesk /跨存储
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.