【问题标题】:How to pass global data in Controller in Angularjs如何在Angularjs中的Controller中传递全局数据
【发布时间】:2017-11-09 15:24:13
【问题描述】:

我在 AngularjsColdfusion 中有一个应用程序。 感谢我的文件 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 );

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

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

提前感谢您的帮助。

问候

【问题讨论】:

    标签: angularjs coldfusion angularjs-scope


    【解决方案1】:

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

    所以在你的标题中,你可以像这样提供变量:

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

    在您的控制器/组件中,您可以像这样简单地注入这个常量:

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

    这是否是 Coldfusion 中的有效解决方案(具体而言,通过 &lt;script&gt;-tag 将会话值插入 javascript)我不知道,但我看不出它不应该工作的任何原因。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2015-04-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多