Angular JS and partials
Asked Answered
C

3

32

Is it possible to embed html page in another one in angular js?

If so, how to do it?

Here in their tutorial, the partial is not embedded in the page but it's like different page where you go when you click on one of the items. (see demo)

Chopping answered 6/12, 2012 at 10:6 Comment(0)
B
32

Yes, you can do it using ngInclude directive.

See the docs and example here: https://docs.angularjs.org/api/ng/directive/ngInclude

Bluefield answered 6/12, 2012 at 10:46 Comment(5)
That's terrible. Is there no way to include a partial without invoking a new request, for example, as a reusable fragment in the initial HTML payload?Bo
Exactly what I needed. Obviously, this should be used sparingly but it worked perfectly to repurpose my login form.Varney
@davidgoli, as far as I know, angular caches loaded templates to avoid subsequent requests.Parthinia
@Bo You can define templates in the same page with a script tag, see docs.angularjs.org/api/ng.directive:scriptBesprent
@davidgoli, the ngInclude directive will make a request to the backend for a partial, but if it already exists in the $templateCache, it will grab it from there first. You can add strings of HTML into the $templateCache like so: $templateCache.put('templateId.html', '<div>This is the content of the template</div>'); This should allow you to add special markup to your main index.html that contains the HTML you want to use as a template, and when the JS kicks in, you can read those elements, pull them in as strings, and add them to your $templateCache so angular can render them in.Motorcycle
B
7

If ng-include is not what you need, you might want to check out the angular-ui-router module. It allows you to do nested and parallel views... It is great, flexible, easy to use and well documented. https://github.com/angular-ui/ui-router

Bello answered 20/8, 2013 at 10:3 Comment(0)
L
7

@Wilt is right, but here is a more specific link and a code sample (from https://github.com/angular-ui/ui-router/wiki/Quick-Reference#ui-view )

In your root template:

<div ui-view></div>
<div ui-view="chart"></div> 
<div ui-view="data"></div> 

And in your app.config function

$stateProvider.state("home", {
    views: {
        "": {
            template: "<h1>Some HTML</h1>"
        },
        "chart": {
            templateUrl: "templates/chart.html"
        },
        "data": {
            template: "<data_thing/>"
        }
    }    
})
Literature answered 27/11, 2014 at 21:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.