0

我想做一個指令,保持元素集中。要做到這一點,我只需將聽衆添加到focusout事件中,並在第一時間呼叫focus()。這很好,但如果我轉換到另一個狀態,並且這個指令超出範圍,我不希望它繼續爭取焦點。角度指令能夠知道它何時變得可見嗎?

如果我做了

$rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState) { 

然後我就可以得到通知,但我不知道這是我的渲染指令中的當前狀態。

+0

你可以發佈你的指令代碼嗎? –

回答

0

我找到了解決方案。請閱讀$state.current

angular.module('constant-focus', []) 
.directive('constantFocus', function($rootScope, $state) { 
    // http://stackoverflow.com/questions/25879759/prevent-keyboard-from-closing/25899264#25899264 
    return { 
    restrict: 'A', 
    scope: { 
     constantFocus: '=', 
    }, 
    link: function($scope, element) { 
     const curState = $state.current; 

     const focusFunction = function() { 
     if (!$scope.constantFocus) { 
      unregister(); 
      element[0].blur(); 
     } else { 
      element[0].focus(); 
     } 
     }; 

     /* jslint latedef:false */ 
     const unregister =() => { 
     element[0].removeEventListener('focusout', focusFunction); 
     }; 

     const register =() => { 
     element[0].addEventListener('focusout', focusFunction); 
     }; 

     $scope.$watch('constantFocus', enabled => { 
     if (enabled) { 
      register(); 
     } 
     focusFunction(); 
     }); 

     $rootScope.$on('$stateChangeStart', function(event, toState, toParams, fromState) { 
     if (fromState === curState) { 
      unregister(); 
     } else if (toState === curState) { 
      register(); 
     } 
     }); 
    }, 
    }; 
}); 
+0

這是不夠的。您還需要監聽'$ scope'的'$ destroy'來移除$ stateChangeStart偵聽器。否則,如果你離開這個狀態然後回來,你會有兩個狀態監聽器。 –

0

使用該指令的$scope$destroy事件分離聽衆。您可以在鏈接或控制器功能中執行此操作。

$scope.$on('$destroy', function() { 
    // Detach focusout listener here 
}); 
+0

這是不夠的,因爲如果我的視圖被緩存,'$ destroy'事件永遠不會被觸發,並且監聽器將繼續爭取焦點。 –

+0

'cached'是什麼意思? –

+0

對不起,我正在使用Ionic,它是一個位於角度頂部的圖層,它在HTML中緩存我的視圖。請參閱http://ionicframework.com/docs/api/directive/ionNavView/ –

相關問題