Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular JS: include partial HTML inside another ng-include

I'm using an index.html created with Yeoman, that looks something like this:

<html>
  <head>...</head>
  <body>

    <div ng-include="'views/main.html'"></div>

  </body>
</html>

Now, I know that I cannot use an ng-include inside another ng-include, so I don't even try that, but that's the objective that I want to achieve.

I'm using ui.router in my main.html for the nested views, but I cannot do something like this:

<header class="header">
  <!-- Rather long HTML code that I would like to put in
       a separate file like 'views/parts/header.html' -->

</header>

<div ui-view="" class="container"></div>

One naive solution would be to eliminate the first ng-include and use it in the main.html for header, footer and stuff like that.

So, hit me with what you've got, but not with that!


Edit: this is what I would love to have (but can't, since I'm already inside an ng-include)

  <div ng-include="'views/parts/header.html'"></div>
  <div ui-view="" class="container"></div>
like image 986
domokun Avatar asked Aug 22 '14 08:08

domokun


1 Answers

If I do understand you properly, that all is possible. As described here:

  • stateprovider in angularjs - not rendering the ui-view
  • and shown here in this plunker

At the end, we can use both worlds, but we have to do one more thing:

app.controller('MainCtrl', function($scope, $state, ....){
   $state.go("/");
});

Because the ng-include and ui-router startup do not match together. We have to force state reload once the target (i.e. the content of our <div ng-include="'views/main.html'"></div>) is available.

NOTE: expecting the content of main.html like this:

<div ng-controller="MainCtrl">
    ...
    <div ui-view></div>
</div>

That should solve the issue...

EXTEND: How to re-include?

The ui-router power here seems to be unlimited. We can *(re)*use the ng-include again, inside of the ui-view. So instead of this:

<div ng-include="'views/parts/header.html'"></div>
<div ui-view="" class="container"></div> // e.g. filled by content.html

We can move the header into the view itself content.html

<div>
  <div ng-include="'views/parts/header.html'"></div>
</div>

Observe that here

like image 71
Radim Köhler Avatar answered Nov 10 '22 21:11

Radim Köhler