user2944669
user2944669

Reputation: 165

UI-Router : Can I get always the same controller?

I'm using UI-Router to have some "menus" in my application.

$stateProvider.state("list"
    url: "/Focales"
    templateUrl: "/demo/focals.html"
    controller: FocalCtrl)
  $stateProvider.state("collection"
    url: "/Collections"
    templateUrl: "/demo/collections.html"
    controller: CollectionCtrl)

In my CollectionCtrl, I trigger a processing done on server and just waiting to display the information like this (CoffeeScript)

Progress = $resource('/collections/getProgress')

$scope.getProgress = () ->
    prg = Progress.get {}, ->
        $scope.currentProgress = prg
        $scope.getProgress() if prg.end isnt true

My issue : When the user moves to Focal and goes back to CollectionCtrl, I have a new instance of CollectionCtrl. So as far as I understand, the $scope.getProgress code still receives data but for the PREVIOUS CollectionCtrl (so the display is not updated...)

Is it possible to get the previous Controller rather than a new "instance" of the CollectionCtrl ? Why is a new CollectionCtrl created ? What's the best approach: So I'm tempted to have a state data to store the current $scope so I could do $state.currentScope = prg rather than $scope.currentProgress = prg. Is it a good approach ?

Thanks !

Upvotes: 3

Views: 1891

Answers (1)

musically_ut
musically_ut

Reputation: 34288

The best approach to take here is to define a service which will communicate with the server and possibly cache the results. This service can be injected in the Controllers and the controllers can ask it for the progress, probably using $watch, though providing the service with a callback may also suffice, and update the UI based on that.

Controllers should be ephemeral and one should not rely on them being singleton-ish objects in Angular. Importantly, they should not contain any state apart from that needed by the template they are supporting. The are created again when the route becomes active so that we can write comparatively simpler code, initializing the $scope once and rest assured that it will contains as fresh information (w.r.t the route) for the template as possible. This also avoids memory leaks if a controller is kept around for each route like /app/:object_id and the user switches routes often.

Upvotes: 2

Related Questions