Search code examples
angularjsangular-ui-routernested-views

Changing states with nested views and a default nested state on page load


I have a Angular App with nested ui-views. On the Main page I have a sub menu with two links that render on the main page. I have Menu1 that displays a list and would like to have that list shown as default on page load. I also have Menu2 that displays a different list once clicked but is not the default view.

I've gotten the nested views to work slightly with errors. I can change only to one state on load and cannot change states back and forth. I'm getting a 404 error after one of the nested views have been clicked, the other returns a 404 error.

Also how do I have a nested view render as the default view on load? Like if I wanted menu1 to render in the ui-view as default when the main page is loaded.

app.js

$stateProvider
  .state('/', {
    url: '/index',
    templateUrl: '/index',
    controller: 'indexCtrl'
  })
  .state('/main', {
    url: '/main',
    templateUrl: 'main',
    controller:   'mainCtrl'
  })
  .state('/main.menu1', {
    url: '/menu1',
    templateUrl: "menu1",
    controller: 'menu1Ctrl'
  })
  .state('/main.menu2', {
    url: '/menu2',
    templateUrl: "menu2",
    controller: 'menu2Ctrl'
  });

controllers

app.controller('menu1Ctrl', ['$scope', function($scope) {
    $scope.livenow = [
    { name: 'user1',
    status: 'online'
    },
    { name: 'user2',
    status: 'online'
    },
    { name: 'user3',
    status: 'online'
    },
    { name: 'user4',
    status: 'online'
    },
    { name: 'user5',
    status: 'online'
    }
    ];
}]);
app.controller('menu2Ctrl', ['$scope', function($scope) {
$scope.livenow = [
{ name: 'user6',
    status: 'offline'
    },
    { name: 'user7',
    status: 'online'
    },
    { name: 'user8',
    status: 'offline'
    },
    { name: 'user9',
    status: 'online'
    },
    { name: 'user10',
    status: 'offline'
    }
    ];
}]);

main.html

<div class="section2 col-md-12">
    <div class="row">
        <div class="section2nav col-md-offset-4 col-md-4">
            <a ui-sref='/main.menu1'> menu1 </a> | <a ui-sref="/main.menu2"> menu2 </a>
            <ui-view></ui-view>
        </div>
    </div>

Solution

  • You want to remove the slash on each state. For example,

    .state('/main', { should be .state('main', {