如何在 onblur 事件中获取 $scope 或 $element 并在 onblur 事件中获取 运行 函数?

How to get $scope or $element in an onblur event and run a function in an onblur event?

我向所有输入字段添加了一个 onblur 事件,我想在 onblur 事件 运行 时获取 $scope$element .但是当我使用 this.$element 获取元素时,我得到 undefined.

当我只记录这个时,我得到了输入标签。 如何在 onblur 事件中获得 $scope$element

代码:

constructor($document, $element, $scope) {
   this.$document = $document;
   this.$element = $element;
   this.$scope= $scope;
}

FunCall() {
  const formElements = this.$element[0].querySelectorAll('input');
  const watchElement = angular.element(formElements[0]);
  console.log(this);

  watchElement[0].onblur = function() {
    console.log(this); // html input element
    console.log(this.$scope); // undefined
    console.log(this.$element); // undefined
  };
}

在第一个日志中我得到了正确的,这是控制器。在第二个日志中,在 onblur 事件中,我得到 HTML 元素,并得到 $scope$elementundefined。如何获取控制器,例如 onblur 事件中的第一个控制器?

我想 运行 onblur 事件中的一个函数,但这没有用:

watchElement[0].onblur = function() {
    this.runSecondFunction();
};

runSecondFunction() {
 console.log('test 2nd function');
}

function() in javascript 也是一个构造函数。这就是为什么,你可以通过 new 创建一个对象。例如:

function ImAFunctionButCanBeConstructor() {
  this.foo = 'bar';
  this.print = function() {
    console.log(this.foo);
  }
}

const myObj = new ImAFunctionButCanBeConstructor();
myObj.print();

在事件处理程序的情况下 this 指的是 DOM element

为了避免这种情况(仅当您不需要该引用时),您可以使用箭头函数而不是常规函数 this will refer to the enclosing context,这是class.

class MyComp {
  constructor($document, $element, $scope) {
    this.$document = $document;
    this.$element = $element;
    this.$scope = $scope;

    this.FunCall();
  }

  FunCall() {
    const formElements = this.$element[0].querySelectorAll("input");
    const watchElement = angular.element(formElements[0]);
    //console.log(this);

    watchElement[0].onblur = () => {
      //console.log(this);
      //console.log(this.$scope);
      console.log(this.$element);
    };
  }
}

angular.module("app", []).component("myComp", {
  controller: MyComp,
  template: `
      <input type="text" placeholder="watch me blur" />
    `
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div id="app" ng-app="app">
  <my-comp></my-comp>
</div>

https://codesandbox.io/s/musing-moore-kohg8?file=/src/index.js

不得不提到 有更多方法可以做到这一点


参考资料