How to nest ng-view inside ng-include?
Asked Answered
I

1

18

When trying to add an ng-view inside an ng-include, nothing happens. e.g. in the following code, when themes/midnight/index.html holds an ng-view, no view is rendered:

<ng-include src="'themes/midnight/index.html'"></ng-include>

However, if I use the code below, the view shows twice:

<ng-include src="'themes/midnight/index.html'"></ng-include>
<div ng-view></div>

What is the problem and how can I resolve it?

Inclusive answered 21/5, 2013 at 15:53 Comment(7)
What do you mean "This doesn't show any view related thing:" ?Thermoplastic
I mean ng-view doesn't appear.Inclusive
Are you using template-src in your routes? A bit more code would be appreciable :-). ng-view is for use view $routeProvider.when(, {template-url: '...'});Thermoplastic
of course, ng-view outside of ng-include works. only ng-view inside ng-include doesn't appear. When I'm declare ng-view twice inside and outside of ng-include, it appears twice. Very weird to me.Inclusive
maybe it's because some kind of isolating, something weird happening with prototypal inheritance. Do you have a jsfiddle/plunker?Thermoplastic
I'm actually having the same issue. Did you resolve it somehow?Caseous
@Caseous This is a scope issue. You should see the scope of angularjs. Unfortunately, I did not solve this problem. I decided not to use ng-include.Inclusive
G
30

This problem occurs due a delayed instantiation of ng-view (passing through ng-include). In such case the $route instantiation is delayed as well, and $route will miss the location change event (and routing will not be performed at all).

To bypass this, invoke the $route update function on application initialization:

yourApp.run(['$route', function($route)  {
  $route.reload();
}]);

Further more, it is sufficient to only include $route as a dependency. This will work, too:

yourApp.run(['$route', angular.noop]);

Source: the related issue on github.


Also check out ui-router, which is intended to specifically deal with the issue of nested views.

Greenbrier answered 30/11, 2013 at 20:39 Comment(5)
Funny, but it's actually enough to inject $route in the main controller - this fixed the issue for me ))Panhellenism
@Panhellenism - this is equivalent to declaring it as a dependency for the app.Greenbrier
how do you declare dependency for the app? Is this what you mean: angular.module('Main', [dependencies here]) ?Panhellenism
@Panhellenism - I didn't mean dependency at the app level - just using DI to request the service (as shown in the answer).Greenbrier
that's what I meant, too - just injecting $route fixed it for me, I didn't even have to call $route.reload(). So by adding $route parameter DI kicks in and creates the $route object - and my guess is that something happens in constructor, because that was enough for me. Thanks!Panhellenism

© 2022 - 2024 — McMap. All rights reserved.