Andre Roque Andre Roque - 2 months ago 17
AngularJS Question

AngularJS create slidedown menu

I'm building an AngularJS app, and basically I have a menu on top of my page then when I select an item is supposed to slide down some content of my page and show the menu in that area. I've read something about creating a directive but isn't still clear to me how can I do it. I show an example of my page:

enter image description here

Then when I select an item from the Menu, the static image disapears and gives place to a "sub menu" and the sub menu content itself.

enter image description here

In some cases, where the "SubMenu" + "Content" height is bigger then the height of the image, the rest of the content will slide down.

My main concern is how to show this SubMenu depending on the menu selected (in the black square). My idea was to create some menu template (with all the html and css created) and then just bind the different content to this template and show it on the div that I want (in this case the div that started with the static image). But since AngularJS is new to me I'm having some problems to put it in pratice.

Answer

You can see plunker example here:

https://plnkr.co/edit/xJoF4IuDtJlGzWmTYoqZ?p=preview

And here is the angular code explanation:

angular.module('plunker', []);

function MainCtrl($scope, menuSvc) {
  // main controller sets the menu contents to the service
  menuSvc.putAll([{t:"item1"},{t:"item2"}]);
}


// a very simple menu service that keeps an object of menu items
angular.module('plunker').factory("menuSvc", [ function( ) {
    var items;

    var clear = function(){
        items = {};
    };

    var getAll = function(){
        return Object.keys(items);
    };

    var put = function( item ){
        items[item.t] = item;
    };

    var putAll = function( itemArray, dontClean ){
        if( !dontClean ){
            clear();
        }
        itemArray.forEach(
            function(i){
                put(i);
            }
        );
    };

    clear();
    return {
        put: put,
        getAll: getAll,
        putAll: putAll,
        clear: clear
    };
}]);


// directive that gets its content from the service
angular.module('plunker').directive('menu', function(){

  return {
    restrict: 'E',
    scope: {
    },

    templateUrl: 'menu.html',

    controller: function($scope, menuSvc) {
        $scope.menu = menuSvc.getAll();
    },

    replace: true
  };
});

When content of the menu is updated you may communicate this event to the directive via angular events, so that it will re-read the cotnent fromt he service. See (https://docs.angularjs.org/api/ng/type/$rootScope.Scope) for $on, $emit, $broadcast