我onblur
在所有输入字段中添加了一个事件,并且我想在事件运行时获取$scope
和。但是当我用来获取元素时,我得到了。$element
onblur
this.$element
undefined
当我仅记录此内容时,将获得输入标签。我如何获得$scope
和$element
参加onblur
活动?
码:
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元素,并获取undefined
了$scope
和$element
。我如何获得控制器,就像onblur
事件中的第一个控制器一样?
我想在onblur
事件内部运行一个函数,但这没有用:
watchElement[0].onblur = function() {
this.runSecondFunction();
};
runSecondFunction() {
console.log('test 2nd function');
}
function()
在javascript中也是构造函数。因此,您可以通过创建对象new
。例如:
function ImAFunctionButCanBeConstructor() {
this.foo = 'bar';
this.print = function() {
console.log(this.foo);
}
}
const myObj = new ImAFunctionButCanBeConstructor();
myObj.print();
如果是事件处理程序,this
则是指DOM元素。
为了避免这种情况(仅在不需要该引用的情况下),可以使用箭头函数代替常规函数,因此this
将引用封闭的上下文,该上下文是该类的实例。
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
只需提一下,还有更多的方法可以做到这一点。
参考文献
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句