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)

ParPar
  • 7,355
  • 7
  • 43
  • 56

3 Answers3

32

Yes, you can do it using ngInclude directive.

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

Boern
  • 7,233
  • 5
  • 55
  • 86
matys84pl
  • 8,344
  • 1
  • 18
  • 18
  • 22
    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? – davidgoli May 09 '13 at 01:08
  • Exactly what I needed. Obviously, this should be used sparingly but it worked perfectly to repurpose my login form. – RevNoah Aug 07 '13 at 18:10
  • 9
    @davidgoli, as far as I know, angular caches loaded templates to avoid subsequent requests. – Marcio Cruz Aug 19 '13 at 01:13
  • 4
    @davidgoli You can define templates in the same page with a script tag, see http://docs.angularjs.org/api/ng.directive:script – Joel Cogen Sep 19 '13 at 11:21
  • 6
    @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', '
    This is the content of the template
    '); 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.
    – Harmon Oct 30 '13 at 16:41
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

Wilt
  • 41,477
  • 12
  • 152
  • 203
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/>"
        }
    }    
})
Tom Carchrae
  • 6,398
  • 2
  • 37
  • 36