121

Is it wrong to assume that ngInclude can take a raw path? I keep trying to set my ngInclude as follows:

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

This does not work but if I do something like this it does work.

// HeaderController
app.controller('HeaderCtrl', function($scope){
   $scope.templates = {[
     template: { url: 'views/header.html' }
   ]};

   $scope.template = $scope.templates[0].template;
});

In my index.html

<div ng-controller="HeaderCtrl">
  <div ng-include src="template.url"></div>
</div>

Does ngInclude only except values off of the scope? If so why is it this way and not a straight include of the html partial.

Mistalis
  • 17,793
  • 13
  • 73
  • 97
Chad
  • 18,076
  • 8
  • 31
  • 41

2 Answers2

327

ng-include accepts an expression. If you want to specify the explicit URL directly in there, you have to give a string.

<div ng-include src="'page.html'"></div>
Tushar
  • 85,780
  • 21
  • 159
  • 179
Tosh
  • 35,955
  • 11
  • 65
  • 55
  • Yea just saw that. Examples that I were looking at were using an older version of angular. – Chad Sep 20 '12 at 22:41
  • 45
    Spent a lot of time this afternoon trying to figure this one out. Of *course* it needs to be a string. That makes *complete* sense. – Code Whisperer May 16 '13 at 18:38
  • doesn't work with ngSanitize enabled in the app module. I'm looking for a solution. – Dida Sep 18 '13 at 11:24
  • 4
    One more thing: The page can not have underscores as filename. –  Sep 29 '13 at 23:10
  • @muffin can you elaborate? My filenames have plenty of underscores in them and work fine. – toxaq Sep 29 '13 at 23:25
  • Well, I have lost like one hour because of the damn underscore in the filename! It's strange. I have checked again and if my view has underscore as filename then it wont appear! the value for src attribute is retrieved from the scope! –  Sep 29 '13 at 23:59
  • 5
    Small single quotes solve the problem. I could not see exact change(My poor eye). Please mention add single quotes inside the double quotes in words. – Fizer Khan Oct 15 '13 at 16:32
  • For people who may be finding this answer for newer versions of Angular...the `src` attribute is only applicable if you are using `ng-include` as an element, e.g. ``. If you are using it as an attribute then you shouldn't use the `src` attribute, e.g. `
    `.
    – Lex Mar 27 '16 at 17:23
1

ng-include, as other directives (ng-class, ng-src ...) evaluates an Angular expression from the scope. Without quotes (''), it will search for a variable of the scope.


Note that you don't have to specify the src attribute.

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

Can be rewritted to: (that is simpler)

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

You can also use ng-include as an element:

<ng-include src="'views/header.html'"></ng-include>
Mistalis
  • 17,793
  • 13
  • 73
  • 97