Angular UI Router Reload Controller on Back Button Press [英] Angular UI Router Reload Controller on Back Button Press

查看:19
本文介绍了Angular UI Router Reload Controller on Back Button Press的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个可以有多个可选查询参数的路由:

I have a route that can have numerous optional query parameters:

$stateProvider.state("directory.search", {
                url: '/directory/search?name&email',
                templateUrl: 'view.html',
                controller: 'controller'

当用户填写表单以搜索目录时,$scope 中的一个函数会改变状态,导致控制器重新加载:

When the user fills the form to search the directory a function in the $scope changes the state causing the controller to reload:

 $scope.searchDirectory = function () {
            $state.go('directory.search', {
                name: $scope.Model.Query.name,
                email: $scope.Model.Query.email
            }, { reload: true });                   
        };

controller 中,我有一个条件:if($state.params){return data} 指示是否会查询我的服务.

In the controller I have a conditional: if($state.params){return data} dictating whether or not my service will be queried.

这很好用,除非用户点击浏览器的前进和/或后退按钮.在这两种情况下,状态(路由)都会正确更改查询参数,但不会重新加载 controller.

This works great except if the user clicks the brower's forward and/or back buttons. In both these cases the state (route) changes the query parameters correctly but does not reload the controller.

据我所知,只有在实际路线发生变化时,控制器才会重新加载.无论如何,是否可以仅使用查询参数来使此示例工作,或者我必须使用不断变化的路由?

From what I've read the controller will be reloaded only if the actual route changes. Is there anyway to make this example work only using query parameters or must I use a changing route?

推荐答案

您应该监听成功的页面更改事件 $locationChangeSuccess.查看它的文档 https://docs.angularjs.org/api/ng/service/$location.

You should listen to the event for succesful page changes, $locationChangeSuccess. Checkout the docs for it https://docs.angularjs.org/api/ng/service/$location.

这里也有一个类似的问题的回答 How to detection browser back button click event using角度?.

There is also a similar question answered on so here How to detect browser back button click event using angular?.

当该事件触发时,您可以将在页面加载上运行的任何逻辑放入控制器初始化时需要运行的任何逻辑.

When that event fires you could put whatever logic you run on pageload that you need to run when the controller initializes.

类似于:

$rootScope.$on('$locationChangeSuccess', function() {
    $scope.searchDirectory()
});  

或者更好的设置,例如:

Or better setup like:

var searchDirectory = function () {
    $state.go('directory.search', {
        name: $scope.Model.Query.name,
        email: $scope.Model.Query.email
    }, { reload: true });

$scope.searchDirectory = searchDirectory;

$rootScope.$on('$locationChangeSuccess', function() {
    searchDirectory();
});  

这篇关于Angular UI Router Reload Controller on Back Button Press的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆