简体   繁体   中英

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.

My problem is the persistence of ng-cookie amidst two separate Javascript files. Let's say I have dashboard1.html that is linked to controller1.js and dashboard2.html linked to 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.

Please advise me how to solve this issue.

NOTE : Javascript files have respective ng-app defined and controller for each application.

This is Controller and ng-app part of one module.

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. This is in file controller1.js

Now I am trying to access the same cookie in controller2.js that is all together bound by different 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.

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.

it utilizes window.postMessage() technique to achieve this behavior.

link: zendesk/cross-storage

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM