Angularjs 如何在 Controller 中传递全局数据

How to pass global data in Controller in Angularjs

我在 AngularjsColdfusion[=40 中有一个应用程序=]。 由于我的文件 application.cfc,我在 session 中保存了用户数据。 我想在每个控制器中获取这些数据,以便在我的模板中使用它们。

我已经完成了这个解决方案,但我不确定这是最好的方法,因为我必须在每个控制器中编写相同的行来获取数据并将它们注入模板。

文件application.cfc:

<cfcomponent output="false" extends="RootApplication">

 ..........................................

    <cffunction name="onRequestStart">

        <cfset admin = 0>
        <cfset viewer = 0>
        <cfset author = 0>

        <!--- Authenication is OK --->

        <cfif isdefined('SESSION.username')>

                    <!--------------- CHECK USER ROLES FROM an external system START --------------->


                    <cfhttp url="https://myComponent" method="get" result="result">
                        <cfhttpparam type="header" name="userName" value="#SESSION.username#">
                    </cfhttp>


                    <cfset SESSION.userRoles = #userProfile.VALUES[1].cedarRoles#>

                    <cfloop index="i" from="1" to="#arrayLen(SESSION.userRoles)#">
                        <cfswitch expression="#SESSION.userRoles[i].roleLabel#">
                            <cfcase value="ADMINISTRATOR">
                                <cfset admin = "1">
                            </cfcase>
                            <cfcase value="Author">
                                <cfset author = "1">
                            </cfcase>
                            <cfcase value="Viewer">
                                <cfset viewer = "1">
                            </cfcase>                           
                        </cfswitch>
                    </cfloop>
                    <cfset SESSION.adminRole = admin>
                    <cfset SESSION.authorRole = author>
                    <cfset SESSION.viewerRole = viewer>


                    <!--------------- CHECK USER ROLES FROM an external system START --------------->

            </cfif>

         ..........................................

    </cffunction> 

</cfcomponent>

我的index.cfm:

<!DOCTYPE html>
<html xmlns:ng="http://angularjs.org" ng-app="ContactsApp" class="ng-app:ContactsApp" id="ng-app">
    <head>
        ...............................................
    </head>

    <body>
            ...............................................

            <cfif #SESSION.viewerRole# eq 1>
                <ng-view></ng-view>
            <cfelse>

                <div class="alert alert-danger">
                    <div>
                      <span class="glyphicon glyphicon-alert" aria-hidden="true"></span>
                      <span class="sr-only">Error:</span>
                      You do not have sufficient access rights to access to this section
                    </div>              
                </div>

            </cfif>  
            ...............................................

    </body>
</html>

文件app.js:

var app=angular.module('ContactsApp', ['ngRoute', 'ui.bootstrap']);

// register the interceptor as a service
app.factory('HttpInterceptor', ['$q', '$rootScope', function($q, $rootScope) {
       return {
            // On request success
            request : function(config) {
                // Return the config or wrap it in a promise if blank.
                return config || $q.when(config);
            },

            // On request failure
            requestError : function(rejection) {
                //console.log(rejection); // Contains the data about the error on the request.  
                // Return the promise rejection.
                return $q.reject(rejection);
            },

            // On response success
            response : function(response) {
                //console.log(response); // Contains the data from the response.
                // Return the response or promise.
                return response || $q.when(response);
            },

            // On response failure
            responseError : function(rejection) {
                //console.log(rejection); // Contains the data about the error.
                //Check whether the intercept param is set in the config array. 
                //If the intercept param is missing or set to true, we display a modal containing the error
                if (typeof rejection.config.intercept === 'undefined' || rejection.config.intercept)
                {
                    //emitting an event to draw a modal using angular bootstrap
                    $rootScope.$emit('errorModal', rejection.data);
                }

                // Return the promise rejection.
                return $q.reject(rejection);
            }
        };
 }]);

app.config(function($routeProvider, $httpProvider){
    $httpProvider.defaults.cache = false;
    if (!$httpProvider.defaults.headers.get) {
        $httpProvider.defaults.headers.get = {};
    }

    // disable IE ajax request caching
    $httpProvider.defaults.headers.get['If-Modified-Since'] = '0';

    // Add the interceptor to the $httpProvider to intercept http calls
    $httpProvider.interceptors.push('HttpInterceptor');

    $routeProvider.when('/all-contacts',
    {
      templateUrl: 'template/allContacts.html',
      controller: 'ctrlContacts',       
    })
    .when('/view-contacts/:contactId',
    {
      templateUrl: 'template/viewContact.html',
      controller: 'ctrlViewContacts'
    })  
    .otherwise({redirectTo:'/all-contacts'});  
});    


app.controller('ctrlContacts', function ($scope, $timeout, MyTextSearch, ContactService){

    /* GET THE DATA IN SESSION */   
    $scope.adminRole =  adminRole;
    $scope.authorRole = authorRole;
    $scope.viewerRole = viewerRole;

    alert("adminRole: " + adminRole + " -- authorRole: " + authorRole + " -- viewerRole: " + viewerRole );

    ...................................................
});

app.controller('ctrlViewContacts', function ($scope, $routeParams, ContactService, RequestService, ReportService){

    /* GET THE DATA IN SESSION */   
    $scope.adminRole =  adminRole;
    $scope.authorRole = authorRole;
    $scope.viewerRole = viewerRole;

    alert("adminRole: " + adminRole + " -- authorRole: " + authorRole + " -- viewerRole: " + viewerRole );

    ...................................................
});

你能告诉我如何改进它以在所有控制器中传递这些全局值吗? 您能否告诉我是否可以在具有根作用域的控制器中发送变量以及如何做到这一点?

预先感谢您的帮助。

此致

我不熟悉 Coldfusion,但在其他框架中,我通常通过 constant 提供程序将变量传递给 AngularJS。

因此在您的 header 中,您可以提供这样的变量:

<head>
    ...
    <script>
        <cfoutput>
        angular.module('ContactsApp').constant('SESSION_VARS', {
            username: '#SESSION.username#'
        });
        </cfoutput>
    </script>
</head>

并且在你的 controllers/components 中,你可以像这样简单地注入这个常量:

angular.module('ContactsApp').controller('ContactController', ContactController);
function ContactController(SESSION_VARS){
    this.username = SESSION_VARS.username;
}

这是否是 Coldfusion 中的有效解决方案(具体来说,通过 <script> 标签将 session 值插入 javascript)我不知道,但我可以'看不出它为什么不起作用的任何原因。希望对你有帮助。