hakuna
hakuna

Reputation: 6701

Navigate to another page and a specific element Angularjs

I wanted to navigate from one page to another page and a specific element in the other page on button click. How can i do that ?

My scenario: index.html and periodical.html are the two files, periodical.html have multiple elements. Now on click of a button in index.html, i wanted to navigate directly to a specific element in Periodical.html.I am using $stateProvider and $urlRouterProvider

My state (Working fine until navigating to periodical.html):

.state('page.periodical', {
                url: '/periodical',
                controller: 'PeriodicalController',
                controllerAs: 'periodical',
                templateUrl: 'app/components/page/periodical/periodical.html',
                data: {
                    pageTitle: 'Periodical page',
                    dashboard: 'periodical'
                }
        })

I am doing $state.go('page.periodical'); from index.html controller which is working fine. How can i achieve $state.go('page.periodical#rt_page_element1'); ? this is resulting in error but the element reference #rt_page_element1 is correct.

Upvotes: 0

Views: 674

Answers (1)

Dmitriy Nevzorov
Dmitriy Nevzorov

Reputation: 6078

You have to decorate $stateProvider

angular.module('app').config(['$provide', function ($provide) {

  /**
   * Extend the UI Router $stateProvider, adding the ability to specify an
   * anchor hash as a parameter in the ui-sref directive.
   */
  $provide.decorator('$state', ['$delegate', function ($stateProvider) {

    // Save the orignal function for generating a state's URL.
    var $stateHref = $stateProvider.href;

    // Create our extended function.
    $stateProvider.href = function href(stateOrName, params, options) {
      var hash = '';
      params = params || {};
      var hashParam = params['#'];

      // Check if the anchor parameter was specified.
      if (typeof hashParam !== 'undefined') {
        // Ensure hash parameter is a string and not empty.
        if ((typeof hashParam === 'string' || hashParam instanceof String) && hashParam.length) {
          hash = '#' + hashParam;
        }

        delete params['#'];
      }

      // Return the original parsed URL with the hash appended.
      return $stateHref(stateOrName, params, options) + hash;
    };

    return $stateProvider;
  }]);

}]);

And then

<a ui-sref="page.periodical({'#': IDToScrollTo })">

The exact solution is discribed here

Upvotes: 1

Related Questions