如何将焦点设置为'editableCellTemplate'中使用的自定义指令中的文本字段?

时间:2016-04-08 14:11:36

标签: javascript angularjs angular-ui-grid

我在editableCellTemplate中有一个自定义指令,每当我选择文本时,单元格被选中,当我按下“F2”或双击此单元格时,它会显示自定义指令但指令中的文本字段没有获得焦点。

如何将焦点设置到自定义指令内的文本字段中?

查看this fiddle中的“性别”列。 'TAB'和'SHIFT + TAB'序列无法正常工作,看看在“性别”列下获得焦点到文本字段的不一致。

2 个答案:

答案 0 :(得分:0)

试试这个:

public setFocus(el: string): any {
    var vm = this;
    setTimeout(function () {
        $("#" + el).focus();
        $("#" + el).select();

    }, 100);
}

答案 1 :(得分:0)

我已经使用焦点和模糊等事件修复了这个问题。

查看解决方案here

myApp.directive('focusComponent', ['uiGridConstants', 'uiGridEditConstants',
  function(uiGridConstants, uiGridEditConstants) {
    return {
      require: ['?^uiGrid', '?^uiGridRenderContainer'],
      scope: true,
      restrict: 'E',
      template: '<div><div>Some text</div><input type="text"></div>',
      link: function($scope, element, attrs, controllers) {
        console.log(element);
        console.log(arguments);
        setTimeout(function() {
          angular.element($(element).children().children()[1])[0].focus();
          angular.element($(element).children().children()[1])[0].select();
        }, 10);

        var uiGridCtrl = controllers[0];
        var renderContainerCtrl = controllers[1];

        //set focus at start of edit
        $scope.$on(uiGridEditConstants.events.BEGIN_CELL_EDIT, function() {
          var thisEle = angular.element($(element).children().children()[1])[0];
          thisEle.focus();
          thisEle.select();
          thisEle.style.width = (thisEle.parentElement.offsetWidth - 1) + 'px';
          element.on('blur', function(evt) {
            console.log("blur - element");
            $scope.stopEdit(evt);
          });
        });


        $scope.stopEdit = function(evt) {
          // no need to validate a dropdown - invalid values shouldn't be
          // available in the list
          $scope.$emit(uiGridEditConstants.events.END_CELL_EDIT);
        };

        element.on('keydown', function(evt) {
          switch (evt.keyCode) {
            case uiGridConstants.keymap.ESC:
              evt.stopPropagation();
              $scope.$emit(uiGridEditConstants.events.CANCEL_CELL_EDIT);
              break;
          }
          if (uiGridCtrl && uiGridCtrl.grid.api.cellNav) {
            evt.uiGridTargetRenderContainerId = renderContainerCtrl.containerId;
            if (uiGridCtrl.cellNav.handleKeyDown(evt) !== null) {
              $scope.stopEdit(evt);
            }
          } else {
            //handle enter and tab for editing not using cellNav
            switch (evt.keyCode) {
              case uiGridConstants.keymap.ENTER: // Enter (Leave Field)
              case uiGridConstants.keymap.TAB:
                evt.stopPropagation();
                evt.preventDefault();
                $scope.stopEdit(evt);
                break;
            }
          }
          return true;
        });
      }
    }
  }
]);