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
}
}
})();
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
}
})();
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?
The difference between $broadcast() and $emit() is that the former sends the event from the current controller to all of its child controllers. That means $broadcast() sends an even downwards from parent to child controllers. The $emit() method, on the other hand, does exactly opposite.
$emit() Function. The AngularJS $emit method is used to dispatches an event name upwards and travel up to $rootScope. scope listeners. The $emit propagatesevent name upward and travel upwards toward $rootScope. scope listeners and calls all registered listeners along the way.
The angular JS $watch function is used to watch the scope object. The $watch keep an eye on the variable and as the value of the variable changes the angular JS $what runs a function. This function takes two arguments one is the new value and another parameter is the old value.
$broadcast in AngularJS? $rootScope. $broadcast is used to broadcast a “global” event which can be caught by any listener of that particular scope. The descendant scopes can catch and handle this event by using $scope.
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With