简体   繁体   中英

How to focus on first input field generated using a ng-repeat angularjs

I am generating some input fields dynamically using ng-repeat, which is working fine, but I need to focus on the first input generated by this ng-repeat, the inputs are placed based on their sequenceId values. How to achieve this , I tried writing a directive based on this question, [ Focus on input generated by ng-repeat , which didn't help.

This is my html file.

<body ng-app ng-controller="MyCtrl">
  <div ng-repeat="parameters in inputs | orderBy : 'sequenceId'">
    <div ng-if="parameters.parameterType == 'Text'">
      <input type="text" class="form-control" placeholder="{{parameters.parameterDesc}}" focused-on="$first"/>
      <br/>
    </div>
  </div>

This is its controller.

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

app.controller('MyCtrl', function($scope) {

  var inputArr = '[{"parameterName":"PRIORITY","parameterDesc":"Priority","sequenceId":9,"parameterType":"Text","parameterId":"UpdateCase_PRIORITY"},{"parameterName":"REASON","parameterDesc":"Reason","sequenceId":8,"parameterType":"Text","parameterId":"UpdateCase_REASON"},{"parameterName":"TYPE","parameterDesc":"Type","sequenceId":7,"parameterType":"Text","parameterId":"UpdateCase_TYPE"},{"parameterName":"ORIGIN","parameterDesc":"Origin","sequenceId":6,"parameterType":"Text","parameterId":"UpdateCase_ORIGIN"},{"parameterName":"STATUS","parameterDesc":"Status","sequenceId":5,"parameterType":"Text","parameterId":"UpdateCase_STATUS"},{"parameterName":"SUBJECT","parameterDesc":"Subject","sequenceId":4,"parameterType":"Text","parameterId":"UpdateCase_SUBJECT"}]';
  $scope.inputs = JSON.parse(inputArr);

});

app.directive('focusedOn', ['$timeout', function($timeout) {
  return function($scope, $element, $attrs) {
    function focus() {
      $timeout(function() {
        $element.focus();
      }, 20);
    }

    if (_($attrs.focusedOn).isEmpty()) {
      return focus();
    }
    $scope.$watch($attrs.focusedOn, function(newVal) {
      if (newVal) {
        focus();
      }
    });
  };
}]);

use the following directive

angular.module('myApp', [])

.directive('focusedOn', function() {
  return {
    scope: {
      focusedOn: '='
    },
    link: function($scope, $element) {

      $scope.$watch('focusedOn', function(shouldFocus) {
        if (shouldFocus) {
          $element[0].focus();
        }
      });

    }
  };
});

And your HTML will be

<input type="text" class="form-control" placeholder="{{parameters.parameterDesc}}" focused-on="$index == 0"/>

Thanks to this stakoveflow answer

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM