2016-12-13 7 views
0

トグルボタンが押された後、フォーカスを維持しようとしています。 今、ボタンをクリックすると、フォーカスがページの先頭にジャンプします。私は何が間違っているのか分かりません。トグルボタンのフォーカス処理

HTML

<button ng-if=“test” ng-click=“deactivate()">Deactivate</button> 
    <button ng-if=“!test” ng-click="activate()”>Activate </button> 

JS

$scope.activate = function() { 
      var activateButton = document.activeElement; 
      if ($scope.some.length) { 
       $scope.enableSome($scope.some, true); 
      } 
      activateButton.onclick = function() { 
       activateButton.focus(); 
      }; 
     }; 

$scope.deactivate = function() { 
      var activateButton = document.activeElement; 
      if ($scope.some.length) { 
       $scope.enableSome($scope.some, false); 
      } 
      activateButton.onclick = function() { 
      activateButton.focus(); 
      }; 
     }; 
+0

は 'enableSomeは()' 'test'の値を変更していますか? –

+0

@AlexKはい、ユーザーが[アクティブ化]ボタンをクリックすると、テキストが無効になり、逆の場合は –

答えて

1

あなたが実際にng-if条件(documentation)に基づいて追加/ DOMから削除されている2つのボタンがあります。ここでは

コードです。

非アクティブ化ボタンが追加されている間にアクティブ化ボタンが削除されるため、ボタンのフォーカスが外れています(逆も同様です)。

toggleActivation()メソッドを使用して2つのボタンを1つにリファクタリングすることができます。

var myApp = angular.module('myApp', []); 
 

 
function MyCtrl($scope) { 
 
    $scope.test = false; 
 
    $scope.some = [1, 2, 3]; 
 

 
    $scope.enableSome = function(some, activate) { 
 
    //Do whatever 
 
    console.log('enableSome called with activate = ' + activate); 
 
    } 
 

 
    $scope.toggleActivation = function() { 
 

 
    //Toggle the state 
 
    $scope.test = !$scope.test; 
 
    
 
    if ($scope.some.length) { 
 
     $scope.enableSome($scope.some, $scope.test); 
 
    } 
 
    
 
    //The button is still focused! 
 
    console.log('Focused element: ', document.activeElement); 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> 
 

 
<div ng-app="myApp" ng-controller="MyCtrl"> 
 
    <button ng-click="toggleActivation()"> 
 
    {{test ? "Deactivate" : "Activate"}} 
 
    </button> 
 
</div>

+0

ありがとうございます! @AlexK –

関連する問題