在 AngularJS 中选择单选按钮时聚焦于文本框

Focus on textbox when radiobutton is selected in AngularJS

有人可以告诉我当我单击分配给它的单选按钮时如何将焦点设置在我的文本框上吗?我正在使用 angular js。谢谢你的想法

我为你创造了example

HTML:

<body ng-app="scopeExample">
  <div ng-controller="MyController">
    <div ng-repeat='item in mas'>
      <input type="radio" name='somename' ng-model="item.select" value="true" ng-click='clear(item)'>
      <input type='text' focus='item.select'/>
      <br>
    </div>
  </div>
</body>

Javascript:

angular.module('scopeExample', [])
  .controller('MyController', ['$scope', function($scope) {

    $scope.mas=[
      {id:1,select:false},
      {id:2,select:false},
      {id:3,select:false},
      {id:4,select:false}
      ];

  $scope.clear = function(item){
    $scope.mas.forEach(function(x){
      if(x != item)
        x.select=false;
    });
  }

  }]).directive('focus',['$timeout', '$parse', function($timeout, $parse){

    return {
      link:function (scope, element, attrs) {
            var model = $parse(attrs['focus']);
            scope.$watch(model, function (value) {                
                if (eval(value)) 
                    $timeout(function () {
                        element[0].focus();
                    });                
            });
    }
  }

  }]);

我会为您提供伪代码,您可以根据需要进行修改。目前,该代码只有一个单选按钮,选中该按钮后将聚焦于输入元素。但是,您可以根据需要在列表中的复选框中实现这些。

HTML:

<div ng-controller="MyCtrl">
    <input type="radio" ng-model="focusRadio" value=0>
    <input ng-model="name" focus>
</div>

脚本:

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

myApp.directive('focus', function() {
    return function(scope, element) {
       scope.$watch('focusRadio', 
         function (newValue) { 
            newValue && element[0].focus()
         })
    }      
});

function MyCtrl($scope) {}

这是 plunker:http://plnkr.co/edit/ABHCRIm95EyNUI8nWczh?p=preview。将输入类型更改为复选框以更好地了解功能。