Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular ui router - Share views between states

I'm trying to create a web app where I have an index.html page with three views: header, content and footer.

I'd like the header and footer to be consistent between pages but at the same time not be part of the index.html file.

I'd also like the content view to change depending on the url I've gone to.

Here is my current solution

index.html

<body>
    <header ui-view="header"></header>
    <main ui-view="content"></main>
    <footer ui-view="footer"></footer>
</body>

app.js

$stateProvider
    .state('my-app', {
        abstract: true,
        views: {
            'header': {
                templateUrl: 'partials/shared/header.html',
                controller: "UserController"
            },
            'footer': {
                templateUrl: 'partials/shared/footer.html'
            }
        }
    })
    .state('my-app.home', {
        url: "/",
        views: {
            'content': {
                templateUrl: 'partials/home.html',
                controller: 'HomeController'
            }
        }
    })

When I load the page "/" it shows the header and footer as having loaded correctly and I can see them on the page, but the main content is missing.

Can anyone tell me what I'm doing wrong?

Thanks

like image 392
Tom Avatar asked Feb 10 '26 21:02

Tom


2 Answers

I managed to figure it out.

I had to get the view in my child state to point to the view in the root state explicitly.

To do that I had to point to 'content@'.

Fixed code:

app.js

$stateProvider
    .state('my-app', {
        abstract: true,
        views: {
            'header': {
                templateUrl: 'partials/shared/header.html',
                controller: "UserController"
            },
            'footer': {
                templateUrl: 'partials/shared/footer.html'
            }
        }
    })
    .state('my-app.home', {
        url: "/",
        views: {
            'content@': {
                templateUrl: 'partials/home.html',
                controller: 'HomeController'
            }
        }
    })
like image 141
Tom Avatar answered Feb 13 '26 11:02

Tom


You need a parent for my-app.home :

.state('my-app.home', {
    parent: 'my-app',
    url: "/",
    views: {
        'content': {
            templateUrl: 'partials/home.html',
            controller: 'HomeController'
        }
    }
}
like image 24
Troopers Avatar answered Feb 13 '26 13:02

Troopers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!