Jamie Nordmeyer February 2016

Nesting Angular directives

I'm trying to do something which, in theory, should be simple. I've Googled for the answer, but haven't come across anything yet that has worked. I'm using Angular JS 1.4.9. What I want to happen is to have this:

<site-menu>
   <site-menu-item title="Search" href="#/search"/>
   <site-menu-item title="Reports" href="#/reports"/>
   <site-menu-item title="About" href="#/about"/>
</site-menu>

turn in to this:

<ul>
   <li><a href="#/search">Search</a></li>
   <li><a href="#/reports">Reports</a></li>
   <li><a href="#/about">About</a></li>
</ul>

I want to do this as a directive so that when the user clicks one the links, I can apply an "active" CSS style to the LI element. For the life of me, though, I can't get it to work. To be honest, transclusion and compiling (if either of these are what it takes) has always been my weak point with Angular 1.x.

Anyone have any thoughts?

Thanks in advance!

Answers


Nicolas Del Valle February 2016

I don't see the need of using transclusion or compiling, i made a little directive to manage this so we have something to play with. Next time it would be better if you provide with more details or code example.

Try something like this and let me know:

(function(angular) {
  'use strict';

  angular.module('app', [])
    .directive('siteMenu', [function () {
      return {
        restrict: 'AE',
        scope: {
          menus: '='
        },
        controller: SiteMenuController,
        controllerAs: 'vm',
        bindToController: true,
        templateUrl: 'site-menu-template.html'
      };

      function SiteMenuController() {
        var vm = this;

        vm.selected = 0;

        vm.onClick= function(index) {
          vm.selected = index; 
        };
      }
  }])

  .run(['$templateCache', function($templateCache) {
    $templateCache.put('site-menu-template.html',
      '<ul>' +
        '<li ng-repeat="menu in vm.menus" ng-click="onClick($index)" ng-class="{active: $index == vm.selected}">' +
          '<a ng-href="#/{{ menu }}">{{ menu }}</a>' +
        '</li>' +
      '</ul>'
    );
  }]);
})(window.angular);

Directive usage:

<site-menu menus="['search', 'reports', 'about']"></site-menu>

Post Status

Asked in February 2016
Viewed 2,637 times
Voted 12
Answered 1 times

Search




Leave an answer