我具有用于检查是否允许我的用户查看我的应用程序中的内容的服务。
我这样使用它:
<tab ng-controller="LibraryRTLController" ng-if="authFactory.hasFeature('ReadyToLearn')">
但是,它似乎无法正常工作,因为我将不得不在似乎多余的每个控制器中将其初始化。
所以我的问题是:是否有某种方式可以全局使用服务?
请注意,由于某些原因我无法在这里开始解释,我必须使用它,ng-if
所以属性指令对我没有帮助!
更新
所以我把它添加到我的运行功能:
angular.module('app')
.run(function ($rootScope, AuthService, authFactory, $state) {
$rootScope.authFactory = authFactory;
$rootScope.$on('$stateChangeStart', function (event, next, toParams) {
$state.newState = next;
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
event.preventDefault();
if (AuthService.isAuthenticated()) {
// user is not allowed
} else {
// user is not logged in
window.location.href = "http://" + window.location.hostname
}
}
});
})
调试时,我能够看到它实际上是在正确设置变量。
在我的服务中,我创建了一个仅会发出警报的函数:
function doesWork ()
{
alert('true!');
}
现在回到我的html中,我有:
<tab ng-controller="LibraryRTLController" ng-init="authFactory.doesWork()">
但是没有任何结果吗?
有什么办法可以在全球范围内使用服务吗?
您可以简单地将service公开为$rootScope
属性,这样它就可以在每个模板中使用:
appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) {
$rootScope.authFactory = authFactory;
}]);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句