Search code examples
javascripthtmlangularjsangularjs-ng-include

Undefined Function with Ng-Include in Angular JS


I'm facing a problem with an undefined function in AngularJs and I didn't find any fitting solution on the internet: I try to build a single page website. A few tabs are nested in the index.html with ng-include.

If i open the tab1.html allone the angular-functions work as expected. But if i open the index.html (with the embedded tab1.html) the function is undefined and the angular function dosn't work anaymore.

I would be very thankful if someone could help me!!!

-code below-

index.html

<!--Tab-Container-->
<div lang="en" ng-app="IndexPage" ng-cloak class="tabsdemoDynamicHeight" ng-cloak="">
<md-content>
    <md-tabs md-dynamic-height="" md-border-bottom="">

        <!-- Content TAB 1 -->
          <md-tab label="Tab1">
            <md-content class="md-padding">
                <div ng-include src="'views/tab1.html'"></div>
            </md-content>
          </md-tab>           

        <!-- Content TAB 2 --> 
        ...

      </md-tabs>      
</md-content>
</div>
<script type="text/javascript">angular.module('IndexPage', ['ngMaterial']);</script>

index.js

angular.module('IndexPage',['ngMaterial', 'ngMessages', 'material.svgAssetsCache']);

tab1.html

<body>
<div ng-app="tableapp" ng-controller="Ctrl" >
            <a href="#" editable-text="user.name">{{ user.name || "empty" }}</a>
        </div>
</body>

tab1.js

var tableapp = angular.module("tableapp", ["xeditable"]);

tableapp.run(function(editableOptions) {
  editableOptions.theme = 'bs3'; // bootstrap3 theme. Can be also 'bs2', 'default'
});

tableapp.controller('Ctrl', function($scope) {
  $scope.user = {
    name: 'awesome user'
  };  
});

Solution

  • You can't define an ng-app inside an ng-app, and you definitely can't have multiple <body> tags on the same html page, and this is exacltly what happends when angular injects tab1.html template into your index.html.

    If tab1.html is just a view inside your main app, it can't be in the form of

    <body>
       <div ng-app="tableapp" ng-controller="Ctrl" >
                <a href="#" editable-text="user.name">{{ user.name || "empty" }}</a>
       </div>
    </body>
    

    But more like:

    <div>
       <div ng-controller="Ctrl" >
                <a href="#" editable-text="user.name">{{ user.name || "empty" }}</a>
       </div>
    </div>
    

    And of course inject the tableapp module to your main IndexPage module.