Niel
Niel

Reputation: 2006

How to insert HTML by id using something like AngularJS ng-include

I'm using AngularJS and compiling a directive into my main page. The directive has a set of buttons that change depending on what is happening in the directive. I would like to move the buttons to something like a menu-bar in my page, but the menu-bar is not part of the directive.

Would it be possible to use something like ng-include to insert the buttons in the menu-bar?

An example of what I would like to do:

<body ng-app="myApp" ng-controller="Controller">
    <nav class="navbar">
        <ul class="nav nav-pills">
            <li>
                <button>A permanent button</button>
            </li>
            <div ng-include="#other-buttons></div>
        </ul>
    </nav>

    <my-directive></my-directive>

    <script type="text/javascript">
        angular.module('myApp', [])
        .controller('Controller', ['$scope', function($scope) {
          $scope.data = someData;
        }])
        .directive('myDirective', function() {
          return {
            template: '<div id="other-buttons" ng-switch="data">
                        <div ng-switch-when="this">
                            <li><button>This button</a></li>
                        </div>
                        <div data-ng-switch-when="that">
                            <li><button>That button</a></li>
                        </div>
                      </div>'
          };
        });
    </script
</body

So depending on some data the directive template will be different, which should change the content in the nav-bar. How would doing that work?

Upvotes: 2

Views: 463

Answers (1)

mayacoda
mayacoda

Reputation: 190

You can use $templateCache to set and get templates, and then reference them by the ids you gave them. You can see the examples on the page.

myApp.run(function($templateCache) {
    $templateCache.put('buttons.html', 
                    '<div id="other-buttons" ng-switch="data">
                        <div ng-switch-when="this">
                            <li><button>This button</a></li>
                        </div>
                        <div data-ng-switch-when="that">
                            <li><button>That button</a></li>
                        </div>
                   </div>'
   );
});

and then load to the ng-include with

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

Considering that your directive and controller share the same scope, and that your navbar falls within your controller, they should act the same.

However, if you were to use this setup in different parts of the application that do not share the same scope, I would suggest you set up a service that will bridge the gap between the two.

Upvotes: 1

Related Questions