TrulyXax TrulyXax - 5 months ago 32
TypeScript Question

Call a typescript method when url changed

The following is my typescript angular controller. I want a method to trigger every time when the url changed (even a small part of url e.g. a number).

I made the method what i want to trigger, i have a constructor in the controller. How can i know when to trigger that method and where do i need to call it? Inside the constructor to initialize it?

This is my controller's code:

private returnedClass: Class;
static $inject: Array<string> = ['$scope', 'common', 'repository.class'];
constructor(public scope: any, public common: app.core.Common, public myService: {
getFromDB(): void{
if (location.href.indexOf("classAdd") !== -1 && typeof this.common.itemId !== 'undefined' && this.common.itemId != null)
this.myService.getClassById(this.common.itemId).then((returnedItem: Class) => {
this.returnedClass = returnedItem;
.controller('HeaderNavigationController', HeaderNavigationController);

I want to mention that this controller is 1 time executed, when the entire HTML DOM is loaded (index.html). Do i need a watcher or something? How can i do that?

Thanks in advance


If you are using uiRouter listen for the $stateChangeSuccess event:

constructor(private scope: any, private common: app.core.Common, private myService: {    

    scope.$on('$stateChangeSuccess', () => this.getFromDB());

Side Note it is a good practice to mark your dependancies as private rather than public.