Swailem95 Swailem95 - 11 months ago 90
AngularJS Question

Why can't I ng-include a sidenav?

I created a sidenav using MaterializeCSS and its working fine. I also created a controller for it using angular. However when I try to include the sidenav in another html it doesn't work. I can only see the trigger button but when I click it nothing happens and there are no errors in the console.

Here is the sidenav:


<ul id="slide-out" class="side-nav">
<li><div class="userView" ng-controller = "accountCtrl">
<img class="background" src="img/wood.jpg">
<a href="#!user"><img class="circle" src="img/profile-picture.jpg"></a>
<a href="#!name"><span class="white-text name">{{user.firstName}} {{user.lastName}}</span></a>
<a href="#!email"><span class="white-text email">{{user.email}}</span></a>

<li><a><i class="material-icons">today</i>Today</a></li>
<li><a><i class="material-icons">perm_identity</i>Account</a></li>
<li><a><i class="material-icons">assignment</i>Projects</a></li>
<li><a><i class="material-icons">perm_media</i>Gallery</a></li>

<li><a class="subheader"></a></li>
<li><a class="subheader"></a></li>

<li><div class="divider"></div></li>
<li><a><i class="material-icons">settings</i>Account Settings</a></li>

<!-- This is the button I can see when the file is included -->

<div class="fixed-action-btn" style="bottom: 45px; right: 24px;">
<a class="btn-floating btn-large waves-effect waves-light red button-collapse"
data-activates="slide-out"><i class="material-icons">label_outline</i></a>


And this is the ng-include in another html file.

<div ng-include = "'partials/dashboard.html'" ng-controller = "dashboardCtrl"></div>

I can edit my post and show you the controller but I don't think its very important since i'm not really doing anything. I'm just initializing the sidenav.

Answer Source

The problem is a scoping issue. The ng-include directive creates a new scope that prototypically inherits from of the enclosing scope. The ng-controller directive instantiates the controller on the parent of the new scope.

To have AngularJS build the html without creating a new scope, use a directive.

app.directive("dashboardComponent", function() {
    return {
        templateUrl: 'partials/dashboard.html',
        controller: "dashboardCtrl"



For more information, see AngularJS Wiki -- Understanding Scopes -- ng-include