使用$scope
可以轻松发出事件或观看事件。
(function() {
"use strict";
angular
.module("app")
.controller("Ctrl", [
"$scope",
CtrlDefinition
]);
function CtrlDefinition($scope) {
$scope.$on("change", listenForChange);
function listenForChange(data) {
//do something
}
}
})();
但如果我尝试使用var vm = this
语法,我会警告$on
,$emit
和$broadcast
不是this
的方法。我怎样才能访问它们?我还需要在控制器定义中注入$scope
吗?
(function() {
"use strict";
angular
.module("app")
.controller("Ctrl", CtrlDefinition);
function CtrlDefinition() {
var vm = this;
vm.$on("change", listenForChange); //$on is not a method of vm
}
})();
你可以做这样的事情,但不会打败不必使用$scope
的目的吗?
(function() {
"use strict";
angular
.module("app")
.controller("Ctrl", [
"$scope",
CtrlDefinition
]);
function CtrlDefinition($scope) {
var vm = this;
vm.scope = $scope;
vm.scope.$on("change", listenForChange);
}
})();
如何使用控制器作为语法访问观察者?