Wajahath Wajahath - 1 month ago 15
Javascript Question

Angular Material's md-nav-bar is not working properly with ui-router

I was playing with angular material and ui-router.

Here is the pen.



html:

<md-nav-bar md-selected-nav-item="'browse'" nav-bar-aria-label="navigation links">
<md-nav-item md-nav-sref="projects.browse" name="browse">Browse</md-nav-item>
<md-nav-item md-nav-sref="projects.settings" name="settings">Settings</md-nav-item>
</md-nav-bar>


The issue is, eventhough
md-selected-nav-item="'browse'"
enables the app to activate the
browse
tab by default, It is not showing the ui-router state:
projects.browse
.

But when we click the
browse
tab it shows up. Problem is the routing functionality is not working when the page loads up.

js

$stateProvider
.state({
name: "projects",
url: "/projects",
template: "<h4>this is project page:</h4> <ui-view></ui-view>"
})
.state({
name: "projects.browse",
url: "/browse",
template: "<h3>Browse</h4>"
})
.state({
name: "projects.settings",
url: "/settings",
template: "<h3>Settings</h4>"
});


Obviously I'm missing something.

pen

Answer

Reading the docs it seems that md-nav-sref is actived on clicking the tab:

enter image description here

Here's a work around - CodePen

Markup

<div ng-cloak ng-app="MyApp" ng-controller="MyController">
  <!-- Navbar -->
  <md-content class="md-padding">
    <md-nav-bar md-selected-nav-item="selectedItem" nav-bar-aria-label="navigation links">
      <md-nav-item md-nav-sref="projects.browse" name="browse">Browse</md-nav-item>
      <md-nav-item md-nav-sref="projects.settings" name="settings">Settings</md-nav-item>
    </md-nav-bar>

    <ui-view></ui-view>
  </md-content>
</div>

JS

angular.module('MyApp', ['ui.router', 'ngMaterial', 'ngMessages']);

angular.module('MyApp')

.config(function($stateProvider, $urlRouterProvider, $urlMatcherFactoryProvider) {

    // for handling trailing slashes
    $urlMatcherFactoryProvider.strictMode(false);

    // for any unmatched url, redirect to the default.
  // NOTE: I can't adjust this value to fix this issue.
  //       setting this to "/projects/browse" may fix this issue,
  //       but I cant go with that.
    $urlRouterProvider.otherwise("/projects");

  $stateProvider
  .state({
            name: "projects",
            url: "/projects",
      template: "<h1>this is project page:</h1> Eventhough the browse tab is selected, content of it isn't showing when the page reloads. <ui-view></ui-view>"
  })
  .state({
            name: "projects.browse",
            url: "/browse",
      template: "<h3>Browse</h4>"
  })
  .state({
            name: "projects.settings",
            url: "/settings",
      template: "<h3>Settings</h4>"
  });

})

.controller("MyController", function ($scope, $state) {
  var initTab = "browse";
  $scope.selectedItem = initTab;
  $state.go("projects." + initTab);
})