2016-05-14 66 views
3

我有我用來檢查我的用戶是否被允許在我的應用程序中看到內容的服務。角度使服務無處不在

我用這樣的:

<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()"> 

但是沒有任何結果?

+0

如果用戶沒有權限查看當前元素,您可以將自定義指令注入到您的auth服務中,並且只需刪除元素 –

+0

@ArturGórski是的,但是我需要使用ng-if –

回答

2

有沒有辦法在全球範圍內使用服務?

你可以簡單地暴露服務爲$rootScope屬性,因此它會在每個模板可供選擇:

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) { 
    $rootScope.authFactory = authFactory; 
}]); 
+0

如果該服務位於另一個模塊中,該怎麼辦?那會工作嗎?因爲現在它似乎並沒有工作:( –

+0

是的,$ rootScope對於你的應用程序中的所有模塊都很常見,它應該可以工作,你能複製一個演示嗎?但是,「其他模塊」是主應用程序模塊的一部分,對吧? – dfsq

0

是的,你可以在你注入的依賴主根文件提到的服務名全球訪問服務

appModule.run(['$rootScope', 'authFactory', function($rootScope, authFactory) { 
    $rootScope.authFactory = authFactory; 
}]); 
+0

你剛剛從我的答案複製代碼嗎?尼斯:) – dfsq

+0

@dfsq你做了一個寫代碼,同樣的事情是我在回答我說的只是給參考 –