角度形式 - 元素焦点

Angular formly - Element focus

本文关键字:元素 焦点      更新时间:2023-09-26

我有一个字段包装器,当鼠标悬停时将普通文本转换为输入,我还有一个目录,当它打开时,将焦点放在该字段上。

现在,只要我专注于该字段,我希望

该字段保持打开状态,并在焦点变为假时转换回普通文本。有没有好方法可以做到这一点?

有一个我目前得到的垃圾箱。

包装纸:

template: [
                '<div ng-hide="to.editorEnabled" >',
                    '<div ng-mouseover="to.editorEnabled=true">',
                        '{{to.label}}</br>',
                        '{{to.value}}',
                    '</div>',
                '</div>',
                '<div focus-me="to.editorEnabled" ng-show="to.editorEnabled">',
                    '<formly-transclude></formly-transclude>',
                '</div>'
            ].join(' ')

对焦指令:

app.directive('focusMe', function($timeout, $parse) {
  return {
    link: function(scope, element, attrs) {
      var model = $parse(attrs.focusMe);
      scope.$watch(model, function(value) {
        console.log('value=',value);
        if(value === true) { 
          $timeout(function() {
            element[0].firstElementChild.focus(); 
          });
        }
      });
    }
  };
});

形态字段:

key: 'textField',
        type: 'input',
        templateOptions: {
          label: 'Text',
          type: 'text',
          value:vm.model.textField
        },
        watcher: {
          listener: function(field, newValue, oldValue, scope, stopWatching) {
            if(newValue) {
              if(!newValue || newValue === "") {
                field.templateOptions.value = "Undefined";
              }
              else {
                field.templateOptions.value = newValue;
              }
            }
          }
        }
      }];

在形式上,您可以在模板选项中添加onBlur和onFocus。因此,您可以添加一个名为 focused 的变量,onBlur 将其设置为 false ,onFocus 将其设置为 true

templateOptions: {
      onBlur:'to.focused=false',
      onFocus:'to.focused=true',
      focused:'true'
},

在指令中添加了两个作用域变量modelfucusmodel是你to.editorEnabled调用的变量,focus将是新创建的变量to.focused

scope: {
        model:'=',
        focus:'='
}

稍后在您的指令中,您可以为 focused 变量添加一个额外的观察程序。 scope.$watch("focus", function(value) { if(!scope.focus){ scope.model=false; } });因此,如果焦点丢失,它将scope.model设置为 false,从而使输入消失。

还做了一个JS垃圾桶,所以你可以仔细看看它。

希望这就是你要找的。