[英]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
};
}
在第一个日志中,我得到了正确的信息,即 controller。 在第二个日志中,在onblur
事件中,我得到了 HTML 元素,并得到了$scope
和$element
的undefined
。 如何获得 controller,就像onblur
事件中的第一个一样?
我想在onblur
事件中运行 function ,但这不起作用:
watchElement[0].onblur = function() {
this.runSecondFunction();
};
runSecondFunction() {
console.log('test 2nd function');
}
javascript 中的function()
也是一个构造函数。 这就是为什么,您可以通过new
创建一个 object 。 例如:
function ImAFunctionButCanBeConstructor() { this.foo = 'bar'; this.print = function() { console.log(this.foo); } } const myObj = new ImAFunctionButCanBeConstructor(); myObj.print();
在事件处理程序的情况下, this
是指DOM 元素。
为了避免这种情况(仅当您不需要该引用时),您可以使用箭头 function 而不是常规 function 所以this
将引用封闭上下文,这是 ZA2F2ED4F8DCEBC2CBBDZC2A 的实例。
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
只是不得不提到有更多的方法可以做到这一点。
参考
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.