问题描述
使用$scope
可以很容易地发出事件或监视事件.
Using $scope
it's easy to emit an event or watch for one.
(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
吗?
But if I try to use var vm = this
syntax, I'm warned that $on
, $emit
, and $broadcast
are not methods of this
. How can I access them? Do I still need to inject $scope
in the controller definition?
(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
的目的吗?
You could do something like this, but wouldn't it defeat the purpose of not having to use $scope
at all?
(function() {
"use strict";
angular
.module("app")
.controller("Ctrl", [
"$scope",
CtrlDefinition
]);
function CtrlDefinition($scope) {
var vm = this;
vm.scope = $scope;
vm.scope.$on("change", listenForChange);
}
})();
如何使用控制器作为语法访问观察者?
How can you access watchers with controller as syntax?
推荐答案
为了使用$scope
上存在的任何内容,您不得不注入$scope
.不幸的是,它很简单,这是"as"语法的缺点.
In order to use anything that exists on $scope
, you are forced to inject $scope
. It's unfortunately that straightforward, which is a shortcoming of the "as" syntax.
但是,好消息是,在this
旁边插入$scope
并不会改变控制器作为语法功能的方式,它只是使您能够访问驻留在$scope
上的所有事件管理.
The good news however is that injecting $scope
alongside this
does not change how the controller as syntax functions, it simply gives you access to all of the event management that lives on $scope
.
值得注意的是,这是Angular 2.0中出现问题的主要原因之一...存在一个实际问题,并且$scope
与为解决范围问题而附加的"Controller as"语法之间存在差异在视图中.
It's worth noting that this is one of the primary reasons for what is coming in Angular 2.0...there is a real problem and discrepancy between $scope
and the "Controller as" syntax that was bolted on to solve scoping issues in views.
这篇关于如何使用Controller作为语法访问$ on,$ emit,$ broadcast方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!