Javascript AngularJS 1事件-“;这";回调方法中的变量是窗口
我正在尝试学习使用AngularJS 1.6事件。Javascript AngularJS 1事件-“;这";回调方法中的变量是窗口,javascript,angularjs,events,Javascript,Angularjs,Events,我正在尝试学习使用AngularJS 1.6事件。 我创建了一个已注册到事件的组件: 'use strict'; var module = angular.module("Test", []); module.controller("Controller1", Controller1); Controller1.$inject = ["$scope"]; function Controller1($scope) { var self = this; self.try = fun
我创建了一个已注册到事件的组件:
'use strict';
var module = angular.module("Test", []);
module.controller("Controller1", Controller1);
Controller1.$inject = ["$scope"];
function Controller1($scope) {
var self = this;
self.try = function () {
$scope.$broadcast("test:try");
}
}
module.controller("Controller2", Controller2);
module.component("compo2", {
controller: "Controller2",
});
Controller2.$inject = ["$scope"];
function Controller2($scope) {
var self = this;
this.$onInit = function () {
$scope.$on("test:try", self.try);
}
self.try = function (event, data) {
console.log("Logged event!!!")
}
}
这是我的html文件:
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title></title>
<script src="./Test/angular.js"></script>
<script src="./compoTest.js"></script>
</head>
<body ng-app="Test" ng-controller="Controller1 as ctrl1">
<compo2> T.E.S.T </compo2>
<button ng-click="ctrl1.try();"> Try! </button>
</body>
</html>
T.E.S.T
尝试
但是当调用回调“try”时,我看到this
变量是窗口,而不是组件的控制器
我做错了什么?这是在JS中将对象方法作为回调调用时发生的情况 为避免意外使用
窗口
,请在JS文件开头使用严格模式:
'use strict';
该方法应绑定到上下文:
this.try = function (event, data) {
this....
}.bind(this);
或应使用self
配方:
var self = this;
self.try = function (event, data) {
self....
};
您不能在
try
中使用此
或self
。目前还不清楚您使用的代码与您发布的代码有何不同。我在“try”中设置了一个断点,并使用chrome devtools控制台查看“this”的值。。。我在编辑的版本中使用了“Self”这个词,因为它不等于controllerthis
,除非你绑定(this)。正如答案所解释的,您应该一致地使用bind(this)
或使用self
。因为self
更简单,所以它通常是首选。哎呀……我忘了在$onInit的声明中用“self”替换“this”。谢谢:)