5

I have nested states, with the parent and child state having a separate controller. But only the parent state is getting executed.

I have the url structure: #/restaurant/2/our-food

So, I want it to load the restaurant with the ID 2 and then the child controller load the 'our-food' content and take care of some other functions.

My code is:

var app = angular.module("app", ['ui.router']);
app.config(function ($stateProvider, $urlRouterProvider) {
 $urlRouterProvider.otherwise("/");

$stateProvider
            .state('home', {
                url: '/',
                controller: function($scope, $stateParams) {
                        $scope.setRestaurant(0);
                }
            })
            .state('restaurant', {
                url: '/restaurant/:restaurantId',
                controller: function($scope, $stateParams, $state) {
                    console.log('first');
                    if($stateParams.restaurantId > 0) {
                        $scope.setRestaurant($stateParams.restaurantId);
                    }
                    else {
                        $state.go('home');
                    }
                }
            })
    .state('restaurant.our-food', {
        url: '/our-food',
        templateUrl: 'templates/our-food.html',
                    controller: function() {
                        console.log('second');
                    }
    });

});

1 Answer 1

11

The controller for your 'restaurant.our-food' state is not being executed because its parent state has no template. This means there is no ui-view directive for it to attach its own template and controller. Even if your parent directive doesn't do anything other than setup some state, it needs to provide at the very least a minimal template.

Try adding the following to your 'restaurant' state and see if that makes it work for you:

template: "<div ui-view />"

This is documented in the ui-router docs:

Remember: Abstract states still need their own for their children to plug into. So if you are using an abstract state just to prepend a url, set resolves/data, or run an onEnter/Exit function, then you'll additionally need to set template: <ui-view />'.

https://github.com/angular-ui/ui-router/wiki/Nested-States-%26-Nested-Views

Sign up to request clarification or add additional context in comments.

1 Comment

That did the job! Thanks a lot mate. I had read the documentation, but must of missed that part.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.