[英]How to call a rootscope fuction in html - Angular Js
i have made a rootscope
function in which I am actually logging out the user. 我做了一个
rootscope
函数,实际上我在注销用户。 But I dont know how to call it in a view . 但是我不知道该怎么称呼它。
My functions is 我的职能是
$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;
};
My view is 我的看法是
<button ng-click="$root.logout()">Logout</button>
I have tried $root.logout()
, $rootScope.logout()
but its not working. 我尝试了
$root.logout()
, $rootScope.logout()
但是它不起作用。
It shoud just be available on the scope, since $scope
inherits from $rootScope
. 它应该仅在作用域上可用,因为
$scope
继承自$rootScope
。 Try: 尝试:
<button ng-click="logout()">Logout</button>
UPDATE... 更新中...
Since you are trying to access $rootScope
from outside of any controller, where there is no child $scope
that inherits from $rootScope
then the logout
function won't be automatically available via inheritance (as I had previously suggested). 由于您尝试从任何控制器外部访问
$rootScope
,因此没有子$scope
继承自$rootScope
因此logout
功能将无法通过继承自动使用(如我之前所建议的)。
You'll have to declare the $rootScope.logout
function in the module's run block instead. 您必须改为在模块的run块中声明
$rootScope.logout
函数。 For more information on this, read the Module Loading & Dependencies part of the angular docs. 有关此的更多信息,请阅读angular文档的Module Loading&Dependencies部分。
JS: JS:
var app = angular.module('myApp', []);
app.run(function($rootScope){
$rootScope.logout = function () {
// ...
}
});
Now the logout
function should be available to call like this: 现在
logout
功能应该可以像下面这样调用:
HTML: HTML:
<button ng-click="logout()">Logout</button>
Sample Plunk - Accessing $rootScope where there is no child $scope 示例Plunk-在没有子$ scope的情况下访问$ rootScope
<form ng-controller="Your controller name" ng-submit="logout()">
<button type="submit">Logout</button>
</form>
Make sure you're using the right controller so it's in scope, use ng-submit to pass the function. 确保使用的控制器正确,因此请使用ng-submit传递函数。 Make sure your button is set to type "submit".
确保您的按钮设置为键入“提交”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.