2017-03-02 77 views
0

我有我的菜單指令。 在$ rootScope中,我設置公司和用戶權限。 取決於選定的公司和我呈現菜單的權限。角度1 Ctrl功能從指令後app.run功能

我在app.run函數中設置公司和用戶權限。這工作到目前爲止,但有時菜單指令在服務調用完成之前呈現。 Service Get Call完成後是否有可能呈現菜單指令?

由於

app.run(function($rootScope, $http, $stateParams, $state, $q, goliathCompanyCheck) 
{ 
.... 
.... 
.... 
$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams) { 
    var company_id = toParams.company_id; 
    if (company_id) { 
     var perm = goliathCompanyCheck.get({object: company_id}, 
      function(response){ 
       if (!response || !response.status || response.status == 'ERROR') { 
        $state.go('company_selector'); 
       } 
       $rootScope.currentCompany = response.data.company; 


      }, 
      function(response){ 
       $state.go('company_selector'); 
      }); 
    } 
}); 

});

+0

僅僅是明確的......你展示在app.run沒有設置權限和公司名稱,但代碼,而不是連接最多的事件監聽器到'$ stateChangeStart'事件,這是事件觸發時真正設置權限和公司名稱的事件。 – TSmith

+0

@TSmith yes $ stateChangeStart函數是設置權限的函數。 它被聲明爲app.run函數的底層。 – ghovat

回答

1

我會建議使用UI-Router,而不是在運行模塊的Rootcope上使用它。

這使您可以將它指定爲視圖的依賴項。這樣你的視圖將不會加載,除非CurrentCompany被解析,否則會觸發狀態改變失敗。

在此示例中,您的狀態「應用程序」是您的應用程序的基本狀態,並且需要url中的公司標識才能解析CurrentCompany。在app.html中,您可以擁有菜單組件的所有標記和指令,並且您的頁面可以是「應用」狀態的子視圖,這意味着它們也都可以訪問CurrentCompany依賴項。

退房文檔here

angular.module('app') 
    .config(function ($stateProvider) { 
     $stateProvider 
      .state('app', { 
       url: '/:companyId/' 
       templateUrl: 'app.html', 
       controller: 'AppCtrl', 
       resolve: { 
        //State won't resolve until CurrentCompany does 
        CurrentCompany: function ($stateParams, goliathCompanyCheck) { 
         return goliathCompanyCheck.get({object: $stateParams.companyId}); 
        } 
       } 
      }) 
      .state('app.home', { 
       url: 'home/', 
       templateUrl: 'home.html', 
       controller: 'HomeCtrl' 
      }) 
    }) 
    .controller('AppCtrl', function ($scope, CurrentCompany) { 
     //CurrentCompany gets injected into the controller and you can assign it to scope 
     $scope.CurrentCompany = CurrentCompany; 
    }) 
    .controller('HomeCtrl', function ($scope, CurrentCompany) { 
     //Can inject it into the child state as well if you want 
     //but it's still available on the scope if the view is nested 
    }) 
+0

謝謝。但菜單是在不同的控制器和服務中生成的。 Service MenuService的內部是prepareMenu函數。我試着用你的解決方案,但如果我記錄$ scope.CurrentCompany裏面的服務功能whichs生成菜單取決於權限我得到一個未定義的。 因爲指令在currentCompany設置之前呈現 – ghovat

+0

這是我的服務'angular.module('goliath.menu.services',[])。 service('$ menuItems',function($ rootScope)'如果指定的服務在currentCompany設置後運行,那麼解決方案就可以工作 – ghovat

+0

除非你傳遞它,否則你不能在服務內部訪問$ scope。必須在你的指令控制器或鏈接函數中調用MyService.prepareMenu($ scope.CurrentCompany);然後你可以訪問CurrentCompany作爲參數 –