1

I have is 2 states defined, one "tickets" matching /tickets ...

$stateProvider // define los estados de mi aplicacion
  .state("tickets", { // le asocio propiedades a cada state
      url: "/tickets", // ruta
      templateUrl: "modules/tickets/views/ticketsTemplate.html", // template a usar
      controller: "TicketsController", // controller a usar
      controllerAs : "tickets" // alias para el controller, para utilizar el this
  });

and the other one "tickets.buscar" matching /tickets/:id that uses the same controller as the parent ("TicketsController") ...

.state("tickets.buscar",{
      url: "/:id",
      templateUrl: "modules/tickets/views/ticketsResult.html"
      }
  ) // heredo el controller del padre

In the controller I have a init() function to initialize the needed variables.

this.init = function(){
  this.title = "Tickets";
  this.id = $state.params.id;

  if(this.id){
    this.getTicket(this.id);
  };
};

this.init();

According to what I read on the UI Router docs, there are 3 ways to access a state:

  • through the URL (or following an external link)
  • using $state.go()
  • using ui-sref in the html's

I'm looking for a way to trigger a controller reload so that no matter how the state is accesed, the init gets executed.

I'm aware of the { reload : true } option in $state.go() but that only solves one of the access methods, and also checked this other question but the solution doesn't work, and that $state parameter isn't documented in UI Router's docs.

Community
  • 1
  • 1
nacho_dh
  • 1,847
  • 3
  • 18
  • 27

2 Answers2

1

A good way may be to use the resolve object when creating a state so that the ticket can be automatically set for you. I haven't tested this, but this should work.

.state("tickets.buscar", {
    url: "/:id",
    templateUrl: "modules/tickets/views/ticketsResult.html",
    resolve: {
        ticket: function($state) {
            // return the output of `getTicket`
            // you would need to move the whole method here
        }
    }
}

Then, in your controller, inject the ticket in along with $scope and all that.

angular.module('someModule')
.controller('TicketsController', ['$scope', 'ticket', function($scope, ticket) {
    console.log(ticket);
]);
searsaw
  • 3,492
  • 24
  • 31
-1

I would use the `StateChangeSuccess´ event:

$rootScope.$on('$stateChangeSuccess', 
function(event, toState, toParams, fromState, fromParams){ 
    //initialize things here...
})
Andre Kreienbring
  • 2,457
  • 11
  • 16