javascript - Angular: how do I call a scope method on state change? -
the angular ui-router events statechangesuccess
etc fired @ rootscope
level , code related these events reside in rootctrl
i have 2 states home , about, homectrl
, aboutctrl
on statechange
'about'
want call method in aboutctrl
... how can achieve this?
note: can call $scope.rootctrlmethod
statechangesuccess
code written in rootctrl
, can't same aboutctrl
.
example: rootctrl
:
function($rootscope, $scope){ $scope.somefun = function(){ console.log("called"); } $rootscope.$on('routechangesuccess', function(event, tostate, fromstate,...){ if(tostate.name == '/'){ $scope.somefun(); } } }
a trick here hook event on $scope
, not on *$rootscope*
:
//$rootscope.$on('routechangesuccess', $scope.$on('routechangesuccess', function(event, tostate, fromstate,...){ if(tostate.name == '/'){ $scope.somefun(); } }
and have access method defined on our $scope.
but, in case, need sure, clear hook
var removeme = $scope.$on('routechangesuccess', ... $scope.$on("$destroy", removeme);
so, once our $scope destroyed, won't create memory leaks.
Comments
Post a Comment