[英]How to call a rootscope fuction in html - Angular Js
我做了一个rootscope
函数,实际上我在注销用户。 但是我不知道该怎么称呼它。
我的职能是
$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>
更新中...
由于您尝试从任何控制器外部访问$rootScope
,因此没有子$scope
继承自$rootScope
因此logout
功能将无法通过继承自动使用(如我之前所建议的)。
您必须改为在模块的run块中声明$rootScope.logout
函数。 有关此的更多信息,请阅读angular文档的Module Loading&Dependencies部分。
JS:
var app = angular.module('myApp', []);
app.run(function($rootScope){
$rootScope.logout = function () {
// ...
}
});
现在logout
功能应该可以像下面这样调用:
HTML:
<button ng-click="logout()">Logout</button>
<form ng-controller="Your controller name" ng-submit="logout()">
<button type="submit">Logout</button>
</form>
确保使用的控制器正确,因此请使用ng-submit传递函数。 确保您的按钮设置为键入“提交”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.