2016-03-04 15 views
0

我正在使用angular-ui-router並且有一個控制器與多個$state.go()事件,各種按鈕將導航到其他視圖。

有沒有辦法在任何$state.go()(在此控制器中)事件執行之前檢查條件而不在每個$state.go()函數之前手動添加檢查?

基本上我想檢查你是否處於編輯模式,提示用戶,然後執行相應的操作。

我想知道是否有一個angular-ui-router方法可以幫助我解決這個問題。我知道這可以在不使用angular-ui-router的情況下完成。

+0

也許使用'$ stateChangeStart'事件? – elclanrs

+0

您可以使用'$ scope。$ on()'來監聽'$ stateChangeStart'事件,參見底部的http://angular-ui.github.io/ui-router/site/#/api/ui。 router.state。$狀態 –

回答

1

嗨測試人員:有,如果你注入$狀態到你的控制器,這聽起來像你已經完成...你可以使用$state.current.name。這會給你你是如狀態的當前名稱:

.state('dashboard.welcome', { url: '/welcome', data: { title: 'Welcome to my company', }, permissions: { has: ['authenticated', 'completed'], }, }); 如果你這樣做控制器內:你會得到console.log($state.current.name) =>「dashboard.welcome」。 這有利於您的編輯方案...... if($state.current.name) == 'dashboard.edit'){ $state.go(destination); } else if...

你可能已經從我的例子中注意到的另一件事是權限:這聽起來像你可能會從這個library故宮受益稱爲角權限(這將不可避免地有一天會成爲一個斷開的鏈接)。這很酷。

要使用它,你基本上可以說:用戶是否有這個標準?如果是,他們可以訪問此頁面。否則... redirectTo:'blahblah'。

但在我的頁面中,我根據某些標準進行了很多導航,我將它放在$ parent.controller中,以便您知道具有ui路由器的子狀態將可以訪問其父控制器及其控制器功能,所以我有這樣一個功能:

$scope.switchToState = function(){ 
     if($state.current.name === ''){ 
      var destination = 'formy.firstPage'; 
      var routeParams = {}; 
      if(account.check('mycriteria')){ 
       destination = 'form.secondPageInstead'; 
      } 
      else if(angular.isString(LocalStorage.secondCriteria)){ 
       destination = 'form.otherPage'; 
       routeParams = {id: LocalStorage.secondCriteria}; 
      } 
      ... 
      $timeout(//often needed is the $timeout to wait for DOM to 
       function(){ 
        if(routeParams.slug){ 
         $state.go(destination, routeParams); 
        } 
        else{ 
         $state.go(destination); 
        } 
       } 
      ); 
     } 
    }; 

現在每個孩子控制器,而不是在每個功能$ state.go的結尾說(「地方」)我做$ scope.switchToState(),它的一切航線爲了我。

0

我最終做的是@elclanrs和@Zargold建議的組合。

我設置了一個全局的$scope變量來檢查我是否處於編輯模式。然後在$scope.$on($stateChangeStart ...檢查當前$state的名稱並相應地繼續。

注意我爲$stateChangeStart使用$scope insell $rootScope,因此它只檢查此控制器範圍內的狀態更改。

$scope.$on('$stateChangeStart', function(event, toState, toParams, fromState, fromParams, options){ 
     if($state.current.name === 'dashboard.welcome' && $scope.isInEditMode) { 
      event.preventDefault(); 
      $modal.open({ 
       animation: false, 
       templateUrl: 'modal.html', 
       controller: 'ModalCtrl', 
       size: 'sm', 
       resolve: { 
        onSuccess: function() { 
         return function(){ 
          //continues the state change 
          $scope.isInEditMode = false; 
          $state.go(toState.name, toParams); 
         }; 
        } 
       } 
      }); 
     } 
    }); 
相關問題