angularjs - angular controllerAs(this) equivalent of $scope.$broadcast and $scope.on, -
according answer want fire event controller another
call method of controller controller using 'scope' in angularjs
$scope.$on("myevent", function (event, args) { $scope.rest_id = args.username; $scope.getmaincategories(); });
and in second controller you'd do
$scope.initrestid = function(){ $scope.$broadcast("myevent", {username: $scope.user.username }); };
but don't use $scope in application, controlleras , this. there way fire event without inject scope ? or should inject $scope anyway ?but read in answer using both scope , controlleras bad practice.
it's not possible register $emit
or $broadcast
event without $scope
or $rootscope
being injected in controller.
it indeed bad practice use $scope
variables , functions since instance of controller injected inside $scope
controlleras
syntax.
but there not other choice injecting scope objects if want use these events.
however shouldn't use $emit
or $broadcast
events share data. these events used application wide information (like user has logged in or logged out...etc.)
a practice when using angular events prefer $rootscope.$emit
because $scope
relies on hierarchy of components.
for example:
$scope.$emit
emit parent component.
$scope.$broadcast
broadcast children components.
then $rootscope.$broadcast
broadcast events rootscope scope (which may make code messy real quick)
$rootscope.$emit
preferred registers event application wide , makes available rootscope only. ($rootscope.$on
)
another practice unbind custom events. whenever component or directive unloaded/destroyed, event listener still reside inside rootscope resulting in possible memory leaks.
to unbind event:
var unbind = $rootscope.$on('logout', function(event, data) { console.log('logout', data); }); $scope.$on('$destroy', unbind);
Comments
Post a Comment