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

梦想的初衷 提交于 2019-12-12 15:15:09

问题


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 !


回答1:


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.



来源:https://stackoverflow.com/questions/19893333/ui-router-can-i-get-always-the-same-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!