javascriptjqueryhtmlangularjsangularjs-templates

How to use ng-template in angular?


I'm writing a client-side angular app and I have a question related to the way I can use angular's ng-template.

So, I have this navbar:

<nav class="navbar navbar-inverse" >
        <div class="container-fluid">              
            </div>
            <div class="collapse navbar-collapse" id="myNavbar">
                <ul class="nav navbar-nav">
                    <!--<li class="active"><a href="#">Home</a></li>-->
                    <li class="dropdown">
                        <a class="dropdown-toggle" data-toggle="dropdown" href="#">Events <span class="caret"></span></a>
                        <ul class="dropdown-menu">
                            <li><a href="#">Create Event</a></li>
                            <li><a href="#"></a></li>
                        </ul>
                    </li>
                    <li><a href="#">About</a></li>
                </ul>
                <ul class="nav navbar-nav navbar-right" ng-include="getTemplate()">

                </ul>
            </div>
        </div>
    </nav>

Ok, in the last <ul> tag I use ng-include="getTemplate()", where getTemplate is this function:

<script type="text/javascript">
        $(function () {
            var getTemplate = function () {
                return "notauth";
            }
        })
    </script>

Basically, this will return the same template, but I just want this to work before I add more logic to it.

"notauth" template is:

<script type="text/ng-template" id="notauth">
        <li><a ui-sref="signup"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>
        <li><a ui-sref="login"><span class="glyphicon glyphicon-log-in"></span> Login</a></li>
    </script>

Note that this is inside my index.html page, because I want my navbar to be the same for all views, but change its template according to user state: if user is logged in use auth template, otherwise use notauth template.

Problem is that this doesn't work and I can't figure out what the problem is.


Solution

  • Declare the function using $scope as follows:

      $scope.getTemplate = function () {
           return "notauth" ;
           console.log("notauth")
      }
    

    Then you can call like this:

    <ul class="nav navbar-nav navbar-right" ng-include="getTemplate()">
    

    This works correctly.