我创建了一个 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/