Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Controller on nested state not getting executed

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');
                    }
    });

});

like image 776
Ben Southall Avatar asked Nov 28 '13 00:11

Ben Southall


1 Answers

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

like image 181
Daniel Tabuenca Avatar answered Nov 03 '22 13:11

Daniel Tabuenca