【问题标题】:UI Router: Best way to initialize variables when state is accesedUI 路由器:访问状态时初始化变量的最佳方式
【发布时间】:2015-10-29 13:59:50
【问题描述】:

我定义了 2 个状态,一个“票”匹配 /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
  });

和另一个匹配 /tickets/:id 的“tickets.buscar”使用与父级相同的控制器(“TicketsController”)......

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

在控制器中,我有一个 init() 函数来初始化所需的变量。

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

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

this.init();

根据我在 UI Router 文档上阅读的内容,有 3 种方法可以访问状态:

  • 通过 URL(或通过外部链接)
  • 使用 $state.go()
  • 在 html 中使用 ui-sref

我正在寻找一种方法来触发控制器重新加载,以便无论状态如何被访问,init 都会被执行。

我知道 $state.go() 中的 { reload : true } 选项,但这仅解决了其中一种访问方法,并且还检查了 this other question 但该解决方案不起作用,并且 $state UI Router 的文档中没有记录参数。

【问题讨论】:

    标签: javascript angularjs angular-ui-router


    【解决方案1】:

    一个好方法可能是在创建状态时使用resolve 对象,以便可以自动为您设置票证。我还没有测试过,但这应该可以工作。

    .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
            }
        }
    }
    

    然后,在您的控制器中,注入 ticket 以及 $scope 以及所有这些。

    angular.module('someModule')
    .controller('TicketsController', ['$scope', 'ticket', function($scope, ticket) {
        console.log(ticket);
    ]);
    

    【讨论】:

    • 谢谢,我使用了你的解决方案,它简化了我正在使用的控制器的结构。
    【解决方案2】:

    我会使用 `StateChangeSuccess´ 事件:

    $rootScope.$on('$stateChangeSuccess', 
    function(event, toState, toParams, fromState, fromParams){ 
        //initialize things here...
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多