kingsley
kingsley

Reputation: 21

How to use $urlRouterProvider.rule

OK, this could be a UI-Router bug, or could just be my fault. I posted a question on Git https://github.com/angular-ui/ui-router/issues/2342, no response yet , much appriciate if anyone could help here

if I do somehing like:

angular.module('myapp', [ 'ui.router' ])

    .config(function($stateProvider, $urlRouterProvider){

        $urlRouterProvider.otherwise("/state1");

        $urlRouterProvider.rule(function ($injector, $location) {
            return "/state2";
        });

        $stateProvider
            .state('state1', {
                url: "/state1",
                views: {
                    "mainview": { template: "state1.html" }
                }
            })
            .state('state2', {
                url: "/state2",
                views: {
                    "mainview": { template: "state2.html" }
                }
            });
    })

    .controller('AppCtrl', AppCtrl);

    function AppCtrl(){
    }

Address bar is changed but state2.html is not loaded, there is only a blank page without throwing any errors

Thanks very much for any possible solutions.

Upvotes: 1

Views: 3781

Answers (1)

Radim Köhler
Radim Köhler

Reputation: 123891

Think about the .rule as an AOP filter. It is just an aspect, which

  • is executed always, when url changes,
  • and could adjust that url.

In comparison with otherwise, which is treated as a "last url resolution handler".

So, the best use, as described in the doc, is to introduce a case-insensitive url support:

rule(rule)

Defines rules that are used by $urlRouterProvider to find matches for specific URLs.

  • rule object Handler function that takes $injector and $location services as arguments. You can use them to return a valid path as a string.

example:

var app = angular.module('app', ['ui.router.router']);

app.config(function ($urlRouterProvider) {
  // Here's an example of how you might allow case insensitive urls
  $urlRouterProvider.rule(function ($injector, $location) {
    var path = $location.path(),
        normalized = path.toLowerCase();

    if (path !== normalized) {
      return normalized;
    }
  });
});

There is an example with above stuff

Upvotes: 1

Related Questions