Navigating with Angular Material and md-nav-bar for efficient routing

Currently, I am delving into Angular and have opted to utilize the Angular Material library for my initial application. After tweaking some basic code borrowed from this source, which I adjusted to suit my requirements, I encountered difficulties with routing and md-nav-items.

<html>

<head>
    <title>PRT - CIT</title>
    <meta name="viewport" content="width=device-width, initial-scale=1" </meta>
    <!-- Angular Material style sheet -->
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/angular_material/1.1.0/angular-material.min.css">
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic"> </head>

<body ng-app="MyApp" id="bootstrap-overrides">
    <div ng-controller="AppCtrl" ng-cloak="" class="navBardemoBasicUsage main">
        <md-content class="md-padding">
            <md-nav-bar md-selected-nav-item="currentNavItem" nav-bar-aria-label="navigation links">
                <md-nav-item md-nav-click="goto('queue')" name="queue">Queue</md-nav-item>
                <md-nav-item md-nav-click="goto('detail')" name="detail">Detail</md-nav-item>
                <md-nav-item md-nav-click="goto('request')" name="request">Request</md-nav-item>
                <!-- these require actual routing with ui-router or ng-route, so they won't work in the demo
          <md-nav-item md-nav-sref="app.page4" name="page4">Page Four</md-nav-item>
          <md-nav-item md-nav-href="#page5" name="page5">Page Five</md-nav-item>
          --></md-nav-bar>
            <div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div>
        </md-content>
    </div>

        <script src="node_modules/angular/angular.js"></script>
        <script src="node_modules/angular-resource/angular-resource.js"></script>
        <script src="node_modules/angular-animate/angular-animate.js"></script>
        <script src="node_modules/angular-route/angular-route.js"></script>
        <script src="node_modules/angular-aria/angular-aria.js"></script>
        <script src="node_modules/angular-messages/angular-messages.js"></script>
        <script src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/t-114/svg-assets-cache.js"></script>
        <script src="node_modules/angular-material/angular-material.js"></script>
        <script src="js/site.js"></script>
        <link rel="stylesheet" href="/css/site.css">
</body>

</html>

Within my JavaScript setup:

(function () {
    'use strict';
    var MyApp = angular.module('MyApp', ['ngMaterial', 'ngMessages', 'material.svgAssetsCache', 'ngRoute']).controller('AppCtrl', AppCtrl);

    function AppCtrl($scope) {
        $scope.currentNavItem = 'queue';
    }
    MyApp.config(function ($routeProvider) {
        $routeProvider.when('/', {
            templateUrl: '/index.html'
            , controller: 'AppCtrl'
        }).when('/queue', {
            templateUrl: '/partials/queue.html'
            , controller: 'AppCtrl'
        }).when('/detail', {
            templateUrl: '/partials/detail.html'
            , controller: 'AppCtrl'
        }).when('/request', {
            templateUrl: '/partials/request.html'
            , controller: 'AppCtrl'
        });
    });
})();

I'm puzzled on how to properly route the tabs. There is built-in routing with md-nav-bar, but I've seen examples using both ngRoute and ui-router.

Moreover, I'm unsure about populating my partial views in the

<div class="ext-content"> External content for `<span>{{currentNavItem}}</span>` </div> 

I attempted switching to md-nav-href instead of md-nav-click, yet it only redirected me to pages without filling the content below my tabs/nav-bar. Subsequently, I reverted the JS changes along with that part of the HTML. Despite searching through related queries, none addressed rendering various partials based on the nav-bar item. Any recommendations? Monitoring currentNavItem's value seems like a possible solution, but the implementation process remains unclear.

For reference, here's a link to the Plnker [demo](https://plnkr.co/edit/1ZJu1hjt3brgQwOt1H9I), although the preview may not render correctly.

Additionally, you can view an image of how it appears when running locally [here](https://imgur.com/gallery/g1sYj).

Thank you for any assistance!

Final Edit:

A shoutout to @Searching for aiding me in resolving the issue below. I have updated the Plnker link to reflect the changes. Please be aware that it might experience slight lags due to the base append script.

Answer №1

ngRoute: Utilize the $route service along with the ng-view container to load all your routed pages.

If you do not have a goto() function, simply use basic md-nav-href tags for navigation. The current navigation item can be set using md-selected-nav-item, but it may not be necessary for your setup. Let's proceed with routing in your configuration.

In your index.html file, update your links to resemble this format using md-nav-href:

<md-nav-item md-nav-href="queue" name="queue">Queue</md-nav-item>

In the index.html file, when implementing html5Mode, include the base tag. Instead of manually defining it, insert the following script and ensure that angular.js is loaded before it:

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.js"></script>    
<script type="text/javascript">
angular.element(document.getElementsByTagName('head')).append(angular.element('<base href="' + window.location.pathname + '" />'));
</script>

To enable html5mode in your script, consider the following code snippet within MyApp.config() function:

MyApp.config(function ($routeProvider, $locationProvider) {
    $locationProvider.html5Mode(true)
    $routeProvider.when('/', {
        templateUrl : 'index.html',
        controller : 'AppCtrl'
    }).when('/queue', {
        templateUrl : 'queue_partial.html',//actual location will vary according to your local folder structure
        controller : 'AppCtrl'
    }).when('/detail', {
        templateUrl : 'detail_partial.html',
        controller : 'AppCtrl'
    }).when('/request', {
        templateUrl : 'request_partial.html',
        controller : 'AppCtrl'
    });
});

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

Utilize the capabilities of the Dropbox Core API in Javascript to effortlessly transfer and store files on

I am currently developing a chrome-extension that has the ability to upload files to the user's Dropbox folder. I have implemented AJAX requests in my code to handle file uploads, and it is working fine for text-based file extensions such as .txt, .js ...

Unusual behavior in a for loop with node.js

Trying out some new things with node.js and running into issues with a basic for loop... for (var i = 0; i < 5; i++); {( console.log(i)) } Can anyone explain why I'm seeing 5 in the console? I was anticipating 0,1,2,3,4... ...

What is the best way to pass parameters in jQuery using .on()?

Hello there, I have a slight dilemma :) Could you please advise me on how to pass a parameter to an external JavaScript function using the .on method? Here is the code snippet: <script> var attachedPo = 0; $this.ready(function(){ $ ...

Implement the geocomplete feature following an ajax event

When I click a button, it adds an input box for entering an address. To assist with auto-completion of the address, I'm using the geocomplete plugin. However, I've noticed that the geocomplete functionality only works on input boxes generated wit ...

The issue with the left border color not functioning in JavaScript

Attempting to alter the border-left-color property using this script is resulting in a Uncaught SyntaxError: Unexpected token -. Is border-left-color actually supported? Javascript function logoChange() { var description = new Array (); description[0] ...

Reducing the number of DOM manipulations for websites that heavily utilize jquery.append

Here's a snippet of my coding style for the website: !function(){ window.ResultsGrid = Class.extend(function(){ this.constructor = function($container, options){ this.items = []; this.$container = $($container); ...

What is the solution for setting a regular height to a Bootstrap select when no option is currently selected?

On my webpage, I am incorporating bootstrap select and I want it to be empty initially with a value of "" when the page first loads. This is essential because it is a required field, so if a user attempts to submit the form without making a selec ...

Exploring the AngularJS world: Enhancing user experience with ui-router and

I am seeking a solution for using a single view across multiple pages with a logical structure in Angular. Additionally, I want to implement breadcrumbs for navigation on the homepage. $stateProvider .state('otherwise', { url: ' ...

Modifying the size of an element with D3 when hovering with the mouse

In a previous project, I created a stacked bar chart with some interesting mouseover effects. Now, I want to take it a step further by changing the size of the rectangle that the user hovers over, returning it to its original size once they move away. My ...

Exploring the Google Maps API Search feature

I am currently developing a JavaScript application that interfaces with the Google Maps API. The program has the following requirements: Enable users to input a location. Upon clicking the "find" button, convert the user's entered location into long ...

Sharing a single JSON object among Angular.JS controllers enhances collaboration and boosts efficiency

My current project involves coding a CRUD app using Angular.JS, and I could really use your expertise to move forward. Here is the situation: View 1 (index) retrieves JSONP data from a remote API and saves it. View 2 (master) displays filtered data on a ...

Encountered an issue while trying to extract data from state - property of null cannot

I'm facing an issue trying to show a navigation item only when a specific flag is true. The problem arises when I attempt to extract data from it, as it returns undefined. Below is the code snippet I have created for this scenario: let navigate = useN ...

Secure Social Security Number (SSN) Input Field showing only the final four digits | includes option to show/hide

I need to show only the last four digits of the SSN and mask the rest with asterisks, like: ****-**-7654 Additionally, I want to implement a toggle functionality where users can reveal or hide the masked characters behind the asterisks. <in ...

The Vue.js @click event does not function properly when used in a selection on mobile

I designed a dropdown menu with different options, and when one is selected it updates the "Value" in vue to a specific amount. Then, I display the selected amount in an input field. For example: <select class="form-control" style="max-width: 150px;" ...

What is the reason behind Firefox's disregard of CSS font-size for code tags within pre tags?

There seems to be a discrepancy in how different browsers on Mac OS X 10.11.4 handle font-size. Is this an issue with Firefox, a CSS bug, or am I missing something about CSS? Here's a JSFiddle where you can see the details. In a section like this: &l ...

Supervising ongoing asynchronous tasks within Node.js's promise-based ecosystem

In my Node.js application, I have created a reliable robot program that continuously sends requests to an API. I have taken precautions by handling errors and setting timeouts for promises in order to prevent any issues from occurring. Now, I am looking t ...

Hovering over a class list will modify various element IDs

Is there a way to change the height of an element with id = "header_nav" when hovering over the class "header_nav" li element? Here is the HTML Code: <div class="header_nav" id="header_nav"> <ul id="header_nav_mainmenu"> & ...

Why doesn't "align-self: flex-end" relocate the game board to the bottom of the screen?

Hey there, I am currently working on developing a Connect 4 game and have decided to use a table for the board. To position the board properly, I am utilizing flexbox. Although I have specified align-items as 'flex-end' in order to bring it to th ...

Click-o-Meter: Tracking Button Presses

I’m looking to develop a button click counter that increases every time it is downloaded. I want to implement this functionality without using a database. Here's the code snippet: <?php $counterFile = 'path/to/counter.txt' ; ...

Prevent anchor link click and drag functionality on an HTML page / Swipe through a container containing links

Is there a way to prevent clicking and dragging on a link in a webpage? When you click the left mouse button on a link and drag it, you can unintentionally move the link or open a new tab. I am looking for a way to disable this behavior using JavaScript o ...