2015-03-31 73 views
1

我在每個單元格中都有一個輸入表格,我可以通過單擊按鈕將記錄添加到該表格。 我想專注於創建的最後一條記錄的第一個輸入。 我不知道這是可能的。 如果有人可以幫助我在此...Angularjs,專注於表格中的輸入

function Ctrl($scope) { 
 
    $scope.adresses = []; 
 
    
 
    $scope.add = function() { 
 
    var adr = {ville:null, codePostal:null} 
 
    $scope.adresses.push(adr); 
 
    }; 
 
    
 
}
<!doctype html> 
 
<html ng-app> 
 
    <head> 
 
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.0.2/angular.min.js"></script> 
 
    <script src="script.js"></script> 
 

 
    </head> 
 
    <body> 
 

 
<div ng-controller="Ctrl" > 
 
    <button ng-click="add()"> Add </button> 
 
    <table> 
 
    <tr> 
 
     
 
     <th>ville</th> 
 
     <th>adresse</th> 
 
    <tr> 
 
    
 
    <tr ng-repeat="adresse in adresses"> 
 
     <td> 
 
     <input ng-model="adresse.ville"/> 
 
     </td> 
 
     <td> 
 
     <input ng-model="adresse.codePostal"/> 
 
     </td> 
 
     
 
     
 
    <tr> 
 
    </table> 
 
    
 
</div> 
 

 

 

 

 

 

 
    </body> 
 
</html>

+0

看看[這個問題](http://stackoverflow.com/questions/14833326/how在設置焦點上的輸入字段),我認爲它基本上做你想要的。你可以在'ng-repeat'中使用'$ last'屬性來檢測是否設置焦點。 – 2015-03-31 15:51:07

回答

1

是的,很容易可行的一個指令:

我的例子與您的代碼:http://plnkr.co/edit/aDNdjjBKZHVfTXnLy2VZ?p=preview

// the directive I use 
.directive('focusOnMe', ['$timeout', '$parse', 
     function($timeout, $parse) { 
      return { 
       //scope: true, // optionally create a child scope 
       link: function(scope, element, attrs) { 
        var model = $parse(attrs.focusOnMe); 
        scope.$watch(model, function(value) { 
         // console.log('value=',value); 
         if(value === true) { 
          $timeout(function() { 
           element[0].focus(); 
          }); 
         } 
        }); 
       } 
      }; 
     } 
]); 

HTML:焦點條件是一個布爾值,這裏是元素是否是最後一個。因此,每次添加新行時,都會重新評估條件並分配焦點。

<td> 
     <input ng-model="adresse.ville" focus-on-me="$last"/> 
</td> 
+0

看起來像一個不錯的解決方案,但是...我從模態中添加表格中的元素。當模式顯示時,由於該指令被調用了很多次,後面的表格會凍結。我不能在plunkr中重現這種行爲。所以我想這個問題是特定於我的項目。 – user1260928 2015-04-01 07:59:26

+0

凍結可能僅僅是由於觀察者和一次插入大量html到DOM中。簡單的解決方案是使用vanilla JS查找最後一行,並在每次添加時關注第一個輸入。這樣你完全繞過指令。但是這不會真的加速你的代碼,它會在每次添加代碼時將焦點放在最後一個元素上。可以通過在焦點上創建超時來緩解。但是,ng-repeat與大量數據和觀察者是真正的敵人。 – SoluableNonagon 2015-04-01 15:21:32

4

試試這種方法。

控制器

controller('AppCtrl', function ($scope, $timeout, $element) { 
    $scope.adresses = []; 

    $scope.add = function() { 
    var adr = {ville:null, codePostal:null} 
    $scope.adresses.push(adr); 

    $timeout(function() { 
     $element[0].querySelector('[is-last=true]').focus(); 
    }) 
    }; 
}); 

標記

<input ng-model="adresse.ville" is-last="{{$last}}"/> 

Working Plnkr

+0

看來我不能在我的控制器中注入$元素,我得到一個未知的提供者:$ elementProvider < - $元素錯誤 – user1260928 2015-04-01 07:22:23

+0

這適用於我...您需要添加'$元素'作爲依賴控制器。謝謝! – bostonsqd 2017-06-07 15:47:57