如何关注使用ng-repeat angularjs生成的第一个输入字段

时间:2016-09-14 08:02:02

标签: javascript html angularjs

我正在使用ng-repeat动态生成一些输入字段,这很好,但是我需要关注这个ng-repeat生成的第一个输入,输入是根据它们的sequenceId值放置的。如何实现这一点,我试着写一个基于这个问题的指令, [Focus on input generated by ng-repeat,没有帮助。

这是我的html文件。

<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>

这是它的控制器。

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();
      }
    });
  };
}]);

1 个答案:

答案 0 :(得分:4)

使用以下指令

angular.module('myApp', [])

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

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

    }
  };
});

您的HTML将是

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

感谢this stakoveflow answer