How to exchange data between controllers in AngularJS?

I am doing a project that uses AngularJS. I created partial pages where each page has its own, different controller.

Site structure

/ProjectRoot
    /css
    /js
        angular.js
        jquery.js


    /partials
        login.html
        page1.html

    index.html

index.html

<!DOCTYPE html>
<html ng-app="demoapp" >
<head>
    scripts
</head>
<body ng-controller="maincontroller">   
     <ng-view></ng-view>
</body>
</html>

login.html

<div class="main-page" ng-controller="logincontroller">
    --code---
</div>

Thus, the full login page is displayed as:

<!DOCTYPE html>
    <html ng-app="demoapp" >
    <head>
        scripts
    </head>
    <body ng-controller="maincontroller">   
         <div class="main-page" ng-controller="logincontroller">
            --code---
         </div>
    </body>
    </html>

I need to exchange data between controllers. I tried to use $scope.$parent.variablename, but when I update page1.html, it contains an empty value.

My questions:

  • How to create global variables that I can use throughout the project, i.e. with all partial pages and their controllers (possibly $rootScope)?

  • Is using a cache the best option or not? (security issue)

+4
source share
1

, Angular. (. ), , . - .

:

$scope.$parent.variablename, page1.html .

Angular .

, Angular - (SPA). , , SPA - . , , , .

, sessionStorage. . Angular, , ( "" "" ).

, sessionStorage. , .

( coffeescript), , userToken:

angular
.module 'app'
.service 'storageService', StorageService

class StorageService

    setStorage:(key, value)->
        json =  if value is undefined then null else JSON.stringify value
        sessionStorage.setItem key, json

    getStorage:(key)->
        JSON.parse sessionStorage.getItem key

    userToken:(value=null)->
        if value is null
            @getStorage 'userToken'
        else
            @setStorage 'userToken', value

, ,

, Angular, . , , storageService :

angular
.module 'app'

.controller 'logincontroller', ($scope, storageService)->
    $scope.setUserToken = (token)-> storageService.userToken(token)

.controller 'maincontroller', ($scope, storageService)->
    $scope.userToken = storageService.userToken()
+4

All Articles