Sergei R
Sergei R

Reputation: 721

ui-router: doesn't load states into state

I want to create such a schema:

DOM schema

Navbar state must be always inserted, it have our template and controller.

Content state must insert templates and controllers depending on URL path. Example:

mysite.com/ inserts main.html and mainCtrl.js into Content state.

mysite.com/articles inserts articles.html and articlesCtrl.js into Content state.

My actual try:

//app.js
var app = angular.module('myApp', [
    'ui.router',
    'ngCookies',
    'myApp.content',
    'myApp.main',
    'myApp.navbar',
    'myApp.articles',
]);

app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/');

    $stateProvider
    .state('index', {
            url: '/',
            views: {
                'navbar': {
                    templateUrl: 'templates/navbar.html',
                    controller: 'navbarCtrl'
                },
                'content': {
                    templateUrl: 'templates/content.html',
                    controller: 'contentCtrl'
                }
            }
        })


//contentCtrl.js
angular.module('myApp.content', ['ui.router'])
    .config(['$stateProvider', function ($stateProvider) {
        $stateProvider
            .state('content.main', {
                url: '/',
                views: 'templates/content/main.html',
                controller: 'mainCtrl'
            })
            .state('content.articles', {
                url: '/articles',
                views: 'templates/content/articles.html',
                controller: 'articlesCtrl'
            }
    }])
.controller('contentCtrl', ['$scope', function ($scope) {

}
]);

//index.html
<body ng-app='myApp'>
  <div ui-view="navbar"></div>
  <div ui-view="content"></div>
</body>

//content.html
<h1>Content template</h1>
<ui-view></ui-view>

I see Navbar and Content states, but main and articles don't load into Content state.

How to create this kind of schema?

Upvotes: 1

Views: 103

Answers (1)

Alon Eitan
Alon Eitan

Reputation: 12025

If the navigation must always be present in the page then you can do something like:

<body ng-app='myApp'>
  <div ng-include="templates/navbar.html"></div>
  <div ng-include="templates/content.html"></div>
</body>

Next, in your navbar.html template, include the controller directly from the view, so you won't need a special state for it:

<div ng-controller="navbarCtrl">
   <!-- THE ACTUAL NAVIGATION HTML -->
</div>

Now you should be able to manage only the "real" states of the application and you don't need the content. prefix before the inner states, and in content.html you already have the <ui-view></ui-view> container for loading the actual states.

Upvotes: 1

Related Questions