在ng-repeat中的按钮点击事件中,将焦点设置在文本框上。

10 浏览
0 Comments

在ng-repeat中的按钮点击事件中,将焦点设置在文本框上。

在这种情况下,请帮助我。在ng-repeat中有一个按钮,当按钮被点击时,文本框被启用,我想要将焦点设置在文本框中,并且将焦点设置在文本的末尾。

var app = angular.module('app', []);
app.controller('demoController', function($scope, $timeout) {
  $scope.testFocus = [{'id': 0, 'isShow': false}, {'id': 1,'isShow': false}];
  $scope.buttonClicked = function(f, $index) {
    angular.forEach($scope.testFocus, function(value, key) {
      $scope.testFocus[key].isShow = (value.id == f.id ? true : false );
    });
    $timeout(function () {
         $('.input-'+ $index).focus();
    });
  }
});




  
    
    
    
    
  
  
      
      
  

0
0 Comments

问题的原因是在ng-repeat中,点击按钮时无法将焦点设置到文本框上。解决方法是使用指令来设置焦点,而不是在控制器中进行DOM操作。

首先,我们可以创建一个名为"autoFocus"的指令。代码如下:

.directive('autoFocus', ['$timeout', function($timeout) {

return {

restrict: 'A',

link : function($scope, $element) {

$timeout(function() {

$element[0].focus();

});

}

}

}])

然后,在使用ng-repeat的地方,我们可以添加"auto-focus"属性来使用这个指令。代码如下:

使用这种方法,我们不需要添加jQuery依赖项(因为使用的是内置的jqlite和JavaScript),而且代码更加整洁和可重用。

0
0 Comments

问题:在ng-repeat中的按钮点击事件中,如何在点击按钮后将焦点设置到相应的文本框中。

原因:在ng-repeat中,由于作用域的问题,无法直接在按钮点击事件中设置文本框的焦点。

解决方法:

1. 注入$timeout服务。

2. 使用jQuery的选择器来选中相应的文本框,并使用`focus()`方法设置焦点。

3. 使用`val()`方法来获取文本框的值,并再次使用`val()`方法将其设置回去,以实现将焦点设置到文本框末尾的效果。

具体代码如下:

var app = angular.module('app', []);
app.controller('demoController', function($scope, $timeout) {
  $scope.testFocus = [{'id': 0, 'isShow': false}, {'id': 1,'isShow': false}];
  $scope.buttonClicked = function(f, $index) {
    angular.forEach($scope.testFocus, function(value, key) {
      $scope.testFocus[key].isShow = (value.id == f.id ? true : false );
    });
    $timeout(function () {
         $('.input-'+ $index).focus();
         $('.input-'+ $index).val($('.input-'+ $index).val());
    });
  }
});




  
    
    
    
    
  
  
    

0