AngularJs:如何访问控制器之外的全局变量? [英] AngularJs: How to access global variables outside of controller?

查看:248
本文介绍了AngularJs:如何访问控制器之外的全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个正常功能来访问一个全局变量,这可能吗?

I am trying to access a global variable via a normal function, is it possible?

我已经使用$ rootScope设置一些变种,我试图通过一个回调函数访问此。
这个回调是由控制器进行调用。我并不想通过 $ rootScope 在回调。

I have set some var using $rootScope and I am trying to access this via a callback function. This callback is called from controller. I don't want to pass $rootScope in that callback.

有什么办法来访问 $ rootScope.var

我打开使用的服务,如果它是可能的。

I am open to use service if it is possible.

请建议。

感谢

我试图访​​问rootScope如下:

I am trying to access rootScope as following:

    function fbLandingCtrl($scope, $rootScope) {
    $rootScope.isFBLoggedin = false;
    $scope.login = function() {
       console.log( $rootScope.isFBLoggedin);
       fbHelper.login(getUserInfo);
      };

      function getUserInfo(){
          fbHelper.getUserInfo(updateStatus);
      }
      function updateStatus(userInfo){
          $rootScope.isFBLoggedin = true;
          console.log( $rootScope.isFBLoggedin);
      }
  }

和我的服务是:

    myapp.factory('FBService', [ '$rootScope', function ($rootScope) {
    $rootScope.isFBLoggedin = false; // global variable
    $rootScope.userName = null;
    $rootScope.userEmail = null;

    return {

        getStatus: function() {
            return $rootScope.isFBLoggedin;
        },
        setStatus: function(status) {
            console.log("Status:"+status);
            return $rootScope.isFBLoggedin = status;
        }
       };
}]);

它显示isFBLoggedin下updateStatus FN为真,但它没有反映在视图

it is showing isFBLoggedin as true under updateStatus fn but it is not reflecting on view

我打印 {{} isFBLoggedin} ,但TS显示出假

I am printing {{isFBLoggedin}} but is ts showing false

最后,它的工作。

我跟着@ dluz的解决方案。

I followed @dluz's solution.

我也用 $ rootScope。$应用(函数(){}})渲染意见

推荐答案

请不要使用$ rootScope定义任何功能 - 这是非常糟糕的做法。请记住,$ rootScope是一个全局变量毕竟。

Please don't use the $rootScope to define any function - it's really bad practice. Remember that $rootScope is a global variable after all.

您可以通过这样的服务获得$ rootScope:

You can get the $rootScope via service like this:

<!doctype html>
 <html lang="en" ng-app="myApp">
  <head>
<meta charset="UTF-8">
<title>Document</title>
  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

  <script>

     var myApp = angular.module('myApp', []);

      myApp.controller('myAppCtrl', ['$scope', 'myService', function ($scope, myService) {

       console.log(myService.getData());

}])

        myApp.factory('myService', [ '$rootScope', function ($rootScope) {

       return {

        getData: function() {
            return $rootScope;
        }
       };
      }])


    </script>

  </head>
  <body ng-controller="myAppCtrl">

   </body>
   </html>

$ rootScope存在,但它可用于邪恶

在作用域角形成了一个等级,从中典型根范围在树的顶端继承。通常这可以被忽略,因为大多数的观点有一控制器,因而一个范围自己的,

Scopes in Angular form a hierarchy, prototypically inheriting from a root scope at the top of the tree. Usually this can be ignored, since most views have a controller, and therefore a scope, of their own.

偶尔有要进行全局对整个应用程序的数据块。对于这些,你可以注入$ rootScope并设置它的值像任何其他范围。由于示波器从根继承的范围,这些值将提供给连接到像NG-节目,就像在本地范围$值指示除权pressions。

Occasionally there are pieces of data that you want to make global to the whole app. For these, you can inject $rootScope and set values on it like any other scope. Since the scopes inherit from the root scope, these values will be available to the expressions attached to directives like ng-show just like values on your local $scope.

当然,全局状态吸你应该谨慎使用$ rootScope,就像你(希望)用任何语言全局变量使用。特别是,不要使用它code,唯一的数据。如果你很想把功能上$ rootScope,它几乎总是更好地把它在需要的地方可以注射,也更容易测试的服务。

Of course, global state sucks and you should use $rootScope sparingly, like you would (hopefully) use with global variables in any language. In particular, don't use it for code, only data. If you're tempted to put a function on $rootScope, it's almost always better to put it in a service that can be injected where it's needed, and more easily tested.

相反,不创建的唯一目的在生活中是存储和返回数据位的服务。

Conversely, don't create a service whose only purpose in life is to store and return bits of data.

已更新答案

A_J,我不知道什么是你的应用程序的场景。我需要看到更多的code给你一个更好的答案,但请看看下面的code。也许可以给你一些想法,你如何设计你的code访问 $ rootScope A 服务里面。

A_J, I am not sure what's the scenario of your application. I would need to see more code to give you a better answer, but please take a look at the code below. Maybe it can give you some idea how you can design your code to access $rootScope inside a service.

preSS按钮登录我在,并看看你的控制台。例如,工作在这里( http://jsbin.com/olOyaHa/1/

Press the button "Log me In" and take a look at your console. Working example here (http://jsbin.com/olOyaHa/1/)

 <!doctype html>
 <html lang="en" ng-app="myApp">
    <head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"></script>

 <script>

     var myApp = angular.module('myApp', []);

     myApp.controller('fbLandingCtrl', ['$scope', '$rootScope', 'loginService', function ($scope, $rootScope, loginService) {

    $rootScope.isFBLoggedin = false;

    $scope.login = function() {
       console.log('Current login status', $rootScope.isFBLoggedin);

       console.log(loginService.getUserInfo());

       loginService.login(loginService.getUserInfo());

       loginService.updateStatus();
      };


     }]);


     myApp.factory('loginService', [ '$rootScope', function ($rootScope) {

    return {

        login: function() {
            console.log('now I am logged in!');
            return $rootScope.isFBLoggedin = true;
        },

        getUserInfo: function() {
            return {
                username: 'xmen',
                role: 'admin',
                logged: 'false'
            };
        },

        updateStatus: function(userInfo){
            $rootScope.isFBLoggedin = true;
            console.log('Current login status', $rootScope.isFBLoggedin);
        }
        };
     }])


    </script>

 </head>
 <body ng-controller="fbLandingCtrl">
    <button ng-click="login()">Log Me In</button>
 </body>
 </html>

这篇关于AngularJs:如何访问控制器之外的全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆