Search code examples
angularjsroutesangular-ui-routerangularjs-ng-route

Route to Submenu Angularjs


In this sample what I need is that in plnkr.co/edit/5FVrydtTPWqYMhhLj03e?p=preview, when I click the Contact Numbers button, It will redirect to the Contact Numbers page in the Contacts.

Im using Angular JS and I hope someone can help me.

scotchApp.config(function($routeProvider) {
    $routeProvider

        // route for the home page
        .when('/', {
            templateUrl : 'pages/home.html',
            controller  : 'mainController'
        })

        // route for the about page
        .when('/about', {
            templateUrl : 'pages/about.html',
            controller  : 'aboutController'
        })

        // route for the contact page
        .when('/contact', {
            templateUrl : 'pages/contact.html',
            controller  : 'contactController'
        });
});

Credits to https://scotch.io/tutorials/angular-routing-using-ui-router for I am forking their example


Solution

  • Your code shows a ng-route example but the link you provide is a ui-router example. ($routeProvider vs $stateProvider).

    If you would be using the $stateProvider from angular-ui-router to define the states you'll be using throughout your application it would probabably be more like the following:

    $stateProvider.state('home', {
      controller: 'mainController',
      url: '/',
      templateUrl: 'pages/home.html'
    });
    $stateProvider.state('about', {
      controller: 'aboutController',
      url: '/about',
      templateUrl: 'pages/about.html'
    });
    $stateProvider.state('contact', {
      controller: 'contactController',
      url: '/contact',
      templateUrl: 'pages/contact.html'
    }); 
    

    You see that a definition of a state uses a string to identify itself with: e.g. :'home', 'contact' etc. You can use the $state service from ui-router and use the \[go(to, params, options)\] method to transition between states in combination with this identifier.

    Convenience method for transitioning to a new state. $state.go calls $state.transitionTo internally but automatically sets options to { location: true, inherit: true, relative: $state.$current, notify: true }. This allows you to easily use an absolute or relative to path and specify only the parameters you'd like to update (while letting unspecified parameters inherit from the currently active ancestor states).

    All you need to do is to couple this to the click event of you button in your maincontroller. That is: inject $state into your mainController and couple an ng-click within your button to a function that executes $state.go().

    <button type="submit" ng-click="$state.go('contact')">Contact Numbers</button>