2016-08-23 11 views
1

ユーザーは質問に複数の回答を入力できるようにしたいので、ユーザーの追加に応じてテキスト入力が繰り返されますより多くの答え。ng-repeatでダイナミック入力を追加すると最後の要素がサファリのフォーカスを奪ってしまう

これはクロムでうまくいきますが、サファリでは、最後の要素が追加されるとすぐにフォーカスを盗み、いくつかの入力に渡って高速タイピングユーザーの回答を広げます。

iOS Safariでは、ブラウザがハングアップするため、さらに悪化します。

はここでここで私はjsfiddleを作成したコントローラ

function AssessmentController($scope, $log) { 
    $scope.answer = {}; 
    $scope.answer.responses = [{id:0, value:""},{id:1, value:""}]; 

    this.addAnswerIfNeeded = addAnswerIfNeeded; 

    // Add answer if the last two answers are non-empty 
    function addAnswerIfNeeded() { 
     var answers = $scope.answer.responses; 

     if ((answers[answers.length - 1].value != '') || 
      (answers[answers.length - 2].value != '')) { 
     addAnswer(); 
     } 
    } 

    // Adds a new answer if this is the last element 
    // isLast is needed to prevent non-lazy evaluation bugs 
    function addAnswer() { 
     $scope.answer.responses.push({ 
      id:$scope.answer.responses.length, value: "" 
     }); 
    }; 
} 

だ形

<form class="form-horizontal sparse" 
     ng-controller="AssessmentController as assessment"> 
    <fieldset> 
     <div class="form-group alt-uses-list" ng-repeat="response in answer.responses"> 
      <label for="answer{{$index}}" class="col-xs-1 control-label">{{$index + 1}}.</label> 
      <div class="col-xs-10"> 
       <input type="text" class="form-control" 
        id="response.uses{{$index}}" 
        autocomplete="off" tabIndex="{{$index + 1}}" 
        autofocus="{{$first}}" ng-model="response.value" 
        ng-change="assessment.addAnswerIfNeeded()"> 
      </div> 
     </div> 
    </fieldset> 
</form> 

ためのコードです。

答えて

1

autofocusの属性はBooleanです。 this linkによれば

必要に応じて最初のパラメータは、ブール値に変換されるように渡される値。 valueが省略された場合、または-0、null、false、NaN、未定義、または空の文字列( "")の場合、オブジェクトの初期値はfalseです。任意のオブジェクトまたは文字列 "false"を含む他のすべての値は、初期値がtrueのオブジェクトを作成します。

ng-repeatの最初の項目ではありません任意の項目をautofocus="false"を生成Booleanオブジェクトのtrueとfalseの値

autofocus="{{$first}}"で真と偽のプリミティブな真偽値を混同しないでください。リンク状態

任意のオブジェクトまたは文字列を含む他のすべての値、「偽」として、の初期値を持つオブジェクトを作成します。

あなたがあなたのコードは、次のように更新することができng-attrディレクティブが含ま角度JSバージョンにアップデートすることができる場合、私は

<form class="form-horizontal sparse" ng-controller="AssessmentController as assessment"> 
    <fieldset> 
    <div class="form-group alt-uses-list" ng-repeat="response in answer.responses"> 
     <label for="answer{{$index}}" class="col-xs-1 control-label">{{$index + 1}}.</label> 
     <div class="col-xs-10"> 
     <input type="text" class="form-control" id="response.uses{{$index}}" autocomplete="off" tabIndex="{{$index + 1}}" ng-attr-autofocus="{{$first||undefined}}" ng-model="response.value" ng-change="assessment.addAnswerIfNeeded()"> 
     </div> 
    </div> 
    </fieldset> 
</form> 

ときng-attr-autofocus="{{$first||undefined}}"実施例を示すために、あなたjsfiddleを更新しましたfalseに評価すると、autofocus属性はundefinedの値を取得し、autofocusがdomから削除されます。

+0

それをしました。助けてくれてありがとう。 – ChristopherJ

関連する問題