导航到另一个页面和特定元素Angularjs

时间:2016-03-18 14:21:34

标签: angularjs ngroute angularjs-ng-route

我想在按钮点击时从一个页面导航到另一个页面,在另一个页面中导航一个特定元素。我怎样才能做到这一点 ?

我的场景:index.html和periodical.html是两个文件,periodical.html有多个元素。现在点击index.html中的按钮,我想直接导航到Periodical.html中的特定元素。我正在使用$stateProvider$urlRouterProvider

我的州(在导航到periodical.html之前工作正常):

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

我正在从index.html控制器做$state.go('page.periodical');,它工作正常。我怎样才能实现$state.go('page.periodical#rt_page_element1');?这导致错误,但元素引用#rt_page_element1是正确的。

1 个答案:

答案 0 :(得分:1)

你必须装饰$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;
  }]);

}]);

然后

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

确切的解决方案被描述为here