javascript - 如何在 html 中调用 rootscope 函数 - Angularjs

标签 javascript angularjs angularjs-rootscope

我创建了一个 rootscope 函数,我实际上在其中注销了用户。但我不知道如何在 View 中调用它。

我的职能是

    $rootScope.logout = function () {
            $cookies.remove('auth_token');
            $cookies.remove('role');
            $cookies.remove('status');
            $cookies.remove('id');
            $location.path('/signin');
//            window.alert("Logout Successfully");
            $rootScope.auth_token = $cookies.get('auth_token');
            $rootScope.role = $cookies.get('role');
            $rootScope.status = $cookies.get('status');
            $rootScope.id = $cookies.get('id');
            $rootScope.keyword_auth_token = 'Bearer ' + $rootScope.auth_token; //Need to store all of them 

            $rootScope.is_loggedin = false;
        };

我的观点是

<button ng-click="$root.logout()">Logout</button>

我已经尝试了 $root.logout()$rootScope.logout() 但它不起作用。

最佳答案

它应该只在范围内可用,因为 $scope 继承自 $rootScope。尝试:

<button ng-click="logout()">Logout</button>

更新...

由于您试图从任何 Controller 外部访问 $rootScope,因此没有从 $rootScope 继承的子 $scope那么 logout 函数将不会通过继承自动可用(正如我之前建议的那样)。

您必须改为在模块的运行 block 中声明$rootScope.logout 函数。有关这方面的更多信息,请阅读 Module Loading & Dependencies Angular 文档的一部分。

JS:

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

app.run(function($rootScope){
  $rootScope.logout = function () {
      // ...
  }
});

现在 logout 函数应该可以像这样调用:

HTML:

<button ng-click="logout()">Logout</button>

Sample Plunk - Accessing $rootScope where there is no child $scope

关于javascript - 如何在 html 中调用 rootscope 函数 - Angularjs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42102159/

相关文章:

javascript - 获取键盘数字键中符号的javascript keycode

javascript - 获得匹配的局域网玩家

javascript转到带有unicode字符的url

angularjs - 根作用域无法在函数中访问

javascript - AngularJS rootScope.$从指令内发出

javascript - 从 jQuery 搜索脚本中删除 on keyup

javascript - 设置溢出时导航栏隐藏不起作用 : auto in a div

angularjs - Angular 在哪里存储指令信息?

python - Angular $routeProvider 不解析 django 变量

javascript - Angular : Reload $rootscope user before initializing controller