Jakub Hlavatý
Jakub Hlavatý

Reputation: 1117

Problems navigating to Angular UI router state

I have a route definition as follows:

        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        });

I have a button that does

$state.go("vehicles.create");

The problem is, that while the URL changes correctly, the page remains the same. Only after the second click, the correct template appears.

Upvotes: 1

Views: 75

Answers (2)

UniCoder
UniCoder

Reputation: 3233

use : for your params and ? to make those params optional if you need.

check the below code snippet, for routing with params.

$stateProvider
.state('contacts.detail', {
    url: "/contacts/:contactId",
    templateUrl: 'contacts.detail.html',
    controller: function ($stateParams) {
        // If we got here from a url of /contacts/42
        expect($stateParams).toBe({contactId: "42"});
    }
})

check this for more clear view on routing.

Upvotes: 0

Jakub Hlavatý
Jakub Hlavatý

Reputation: 1117

After a hint from my colleague I realized, that it was the state definitions that caused the problem. Reordering the states from "more specific" (URL-wise - i.e. /create) to less specific (/{id}) did the trick. So the thing that was wrong was having the more generic URL /vehicles/{id} before the very similar, but less generic /vehicles/create.

So here's the improved version:

        $stateProvider
          .state('vehicles', {
            url: '/vehicles',
            templateUrl: 'foo/bar1.html'
        }).state('vehicles.create', {
            url: '/create',
            templateUrl: 'foo/bar2.html',
            controller: 'VehicleCreateController'
        }).state('vehicles.id', {
            url: '/{id}',
            templateUrl: 'foo/bar3.html'
        });

Upvotes: 1

Related Questions