Developing a sliding menu with AngularJS

Currently, I am developing an AngularJS application. One of the features I am working on involves having a menu at the top of my page that, when an item is selected, will slide down to reveal content specific to that selection in the same area as the menu. While researching how to accomplish this, I came across suggestions to create a directive, but I am still unclear on how to implement it. Below is an example of what my page looks like:

https://i.stack.imgur.com/oZiHl.png

When an item from the menu is selected, the static image disappears and is replaced by a "sub menu" along with its content.

https://i.stack.imgur.com/NEaGq.png

In situations where the combined height of the "SubMenu" and "Content" exceeds that of the image, the remaining content should slide down accordingly.

My primary concern is figuring out how to display this SubMenu based on the selected menu item (highlighted in the black square). My approach was to create a menu template containing the necessary HTML and CSS and then dynamically bind different content to this template to display it within the desired div (in this case, the one initially displaying the static image). However, due to my limited experience with AngularJS, I am encountering difficulties translating this idea into practice.

Answer №1

Check out this plunker example:

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

Here is an explanation of the angular code:

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

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

// A simple menu service that stores 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
  };
});

If the menu content is updated, you can communicate this event to the directive using Angular events, so it will re-read the content from the service. Refer to https://docs.angularjs.org/api/ng/type/$rootScope.Scope for $on, $emit, $broadcast

Example of a listener in the menu controller:

$scope.$on('someEvent', function(){ 
    // Update menu content
    // Trick is to update the menu content, not overwrite it
    // For example:
     $scope.menu.length = 0;
     var newValues =  menuSvc.getAll();
     newValue.forEach(function(x){ $scope.menu.push(x); } );
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Confirming the authenticity of a newly added user input with the help of jQuery

Within my current project, I have implemented validation features for text boxes. When a user clicks on a text box, the border is highlighted. If they click elsewhere without entering any value, the border turns red and an alert pop-up appears. In additio ...

Exploring the potential of Framework7 in Single Page Applications: optimizing performance by preloading

I'm currently working on developing a web application using Framework7. Framework7 offers routing APIs for navigating between HTML pages. It seems that the pages are loaded dynamically through AJAX requests. I am curious if it is possible to preload ...

ClickAwayListener is preventing the onClick event from being fired within a component that is nested

I am encountering an issue with the clickAwayListener feature of material-ui. It seems to be disabling the onClick event in one of the buttons on a nested component. Upon removing the ClickAwayListener, everything functions as expected. However, with it e ...

`How can I trigger a JavaScript event when the content of an input field is modified?`

Currently, I am working on implementing validation in JavaScript. My goal is to provide the user with an alert whenever they modify the value of an input field. <input type="text" name="onchange" id="onchange" size="35" maxlength="50" /> ...

How do I make an AJAX request in Rails without including a question mark in the data?

Currently, I'm attempting to make a GET request to my /routes/ controller in order to retrieve some data. Here is the code snippet I have so far: function fetchMarker(id) { var data; $.ajax({ type: "GET", url: '/routes/&a ...

Once the vue-cli has deployed to the server, the server's requested image path is now located in /dist/ folder

Issue with Image Loading: While the demo successfully loads all resources and uploads images correctly, there is an issue where an extra /dist/ is being requested for image paths, resulting in a 404 error. Demo Link: Configuration of the Demo: vue.conf ...

What is the best way to utilize jQuery for drag and drop functionality to transfer data between multiple divs and automatically update the database when the drop occurs?

Can anyone guide me on using jQuery UI for drag and drop to transfer data between multiple divs? I'm currently working with jQuery in conjunction with an asp.net core api. The task is similar to a calendar system where entries can be moved across di ...

The transitioning period caused the gooey effect to become distorted

I'm currently working on creating a radio button with a gooey effect. The transition looks great, but once it's complete, the colors don't blend well and the edges glow in an odd way. I've been searching for the root of the issue, but ...

Need to specify a parameter type for the input tag in HTML

Currently, I am developing a customized focus method for my webpage using the following script: <script type="text/javascript"> function myFunction() { document.getElementById("name").focus(); } </script> I ...

Managing JSON responses from a server using Javascript

I have encountered various similar issues, but none of them have provided a solution for my specific question. On my server, I generate a JSON string and place it in the response: List<String> list = getSomeList(); JSONArray jsArray = new JSONArray( ...

Repetitive use of multiple submit buttons in AngularJS

i'm currently working with AngularJS Currently facing this issue: view screenshot I have utilized the following HTML code to display submit button for two different types of forms. One for TEXT Form and one for ENUM Form: <div ng-controller="g ...

Modify the path name in Next.js according to the local environment

In my upcoming next.js project, I aim to dynamically alter the URL according to the language selection of the user. By default, the URL for the English language is set to: http://localhost:3000/en/privacy-policy If the language is switched from English ...

I have the latitude and longitude for both the shop and user, and I am looking to display a list of shops in order based

Currently, I have the latitude and longitude for both my shop and the user. My objective is to display a list of shops that fall within the geographic area between the user's location and the shop's coordinates using Sequelize ORM. Can you provid ...

Attempting to fill a collection of JSON entities through a GET call?

When handling a GET request that contains a list of JSON objects, I want to display the data in an input field on the screen using ng-model for data binding. The structure of the JSON get request is as follows: [{"make":"Mahindra","vin":"1987","model":"XU ...

Traversing through objects in react.js

Hello there, I'm currently learning React and JavaScript but facing some challenges with a particular task. Let's dive into it! So, imagine I have an array like this: clients = ["Alex", "Jimmy"] and then I proceed to create another array using th ...

Tips for repairing a side bar and header with CSS when using a JS & jQuery scroller

I am working on a layout design and my goal is to have the left sidebar, right sidebar, and header remain fixed in place. Here is the CSS code I am using : #container { padding-left: 200px; /* Left Sidebar fullwidth */ padding-ri ...

CSS Style in Safari does not conceal Div on Tailwind

When switching the screen from desktop to mobile in ReactJS/Tailwind, I have hidden certain images using the following code: <div className="flex shrink flex-row justify-between w-[60%] h-[25%] sm:w-[95%] sm:h-[52%] mb-[-10px] mt-[-15px] lg:mt-0&qu ...

Placement of BOX alongside each other

Whenever I try to align the green and orange boxes side by side, it doesn't seem to work properly. Even though 1000 divided by 2 equals 500 (by the way, I am new to HTML). I am struggling with understanding positions and sizes in HTML. Here is the HT ...

AngularJS Firebase Login Scope Value Not Retained After Refresh

I have stored my unique username in the variable "$scope" and I am trying to access it from different views once the user logs in, using: However, when I refresh the page immediately after the user successfully signs in, the value of "$scope" goes bac ...

Show or conceal a class

Hello there! I've been attempting to create a toggle effect using an anchor link with an "onclick" event to show and hide content. Despite my efforts with jQuery and JavaScript functions, I just can't seem to figure out the right approach. Here& ...