简体   繁体   中英

Using the browser to navigate back in an angularjs app with ui-router?

Here is my scenario.

  1. Search for customers via "/customers" (app.customers), say I search for "bob"
  2. Click one of the results to get to "/customers/detail/:id" (app.customers.detail).
  3. Hit the back button in the browser, which redirects me to the "/customers" page with no search results.

How can I get it to work so when I hit back I go to the page where the customer search results are displayed using my original search text, "bob"?

I have seen this post but do I really have to create a session service, state history service, and state location service? Seems like there should be a much easier way to get this to work. Thanks.

The correct answer is that you need to change the URL based on the data searched for. When you perform a search for "Bob", change the URL to match that: /customers?q=bob and go to a route that handles that (or just let your one route be able to handle an optional query parameter). This allows you to use the browser's state handler, so that when you go Back to /customers?q=bob , you can handle it.

If you don't want to do it in a way that browsers natively support (urls), you'll have to do it manually, using the services, etc, which is just a pain.

Thanks Dan, I went with your suggestion and now have the search parameters in the URL. This is what the URL looks like now:

localhost/#/customers?searchText=test&pageSize=25&pageNumber=1

..and here is my updated state in ui-router. The params section sets the default values and "squashes" the URL parameters if they match the defaults.

.state("app.customers", {
    url: "/customers?searchText&pageSize&pageNumber",
    params: {
        searchText: { value: "", squash: true },
        pageSize: { value: 25, squash: true },
        pageNumber: { value: 1, squash: true }
    },
    controller: "customersController as vm",
    templateUrl: "customers.html",
    resolve: {
        customerService: "customerService",
        customers: function (customerService, $stateParams) {
            if ($stateParams.searchText) {
                return customerService.search($stateParams.searchText, parseInt($stateParams.pageSize), parseInt($stateParams.pageNumber));
            } else {
                //return empty array and default pager
                return null;
            }
        },
    }
})

..and now on the customer page when the user hits the search button I just do this in the controller's search() method.

$state.go("app.customers", { searchText: vm.searchText, pageSize: vm.pager.pageSize, pageNumber: pageNumber });

This UrlMatcher documentation for ui-router was very helpful. This article was also helpful.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM