如何使用angular-ui-router滚动到页面区域?

Ala*_*an2 3 angularjs angular-ui-router

我有一个网页,上面有一个网格表.显示网格时没有点击行,状态为"home.pages",页面URL显示如下:

http://localhost:1495/subjects/4/admin/words
Run Code Online (Sandbox Code Playgroud)

当用户单击网格中的单词1234的行时,状态将更改为"home.pages.page",其中wordId参数为1234,URL显示如下:

http://localhost:1495/subjects/4/admin/words/1234
Run Code Online (Sandbox Code Playgroud)

当我使用角度ui-router时,是否可以将页面滚动到wordId为1234的行?

Yoa*_*oan 5

您可以使用$anchorScroll服务滚动到页面区域,无论您使用的是angular-ui/ui-router还是ng-route都无关紧要.您只需要为您的行创建一个控制器,在这种特殊情况下,注入必要的服务,如:$ scope,$ stateParams,$ anchorScroll,$ location并声明一个管理滚动逻辑的方法,例如:Template:

<div ng-controller="RowsCtrl">
    <h1>State 1</h1>
    <p>Id: {{id}}</p>
    <hr/>
    <a ui-sref="state1.list">Show List</a>

    <div class="fixed-header">
      <a href="" ng-click="gotoRow(x)" ng-repeat="x in [1,2,3,4,5]">
        Go to row {{x}}
      </a>
    </div>

    <div id="row{{x}}" class="anchor" ng-repeat="x in [1,2,3,4,5]">
      Row {{x}} of 5
    </div>
    <div ui-view></div>
</div> 
Run Code Online (Sandbox Code Playgroud)

角度状态配置ui-router:

angular
  .module('angularApp', [
    'ngAnimate',
    'ngCookies',
    'ngResource',
    'ngRoute',
    'ngSanitize',
    'ngTouch',
    'ui.router'
  ])
  .config(function($stateProvider, $urlRouterProvider) {
    //
    // For any unmatched url, redirect to /state1
    $urlRouterProvider.otherwise("/state1");
    //
    // Now set up the states
    $stateProvider
      .state('state1', {
        url: "/state1/:id",
        templateUrl: "views/partials/state1.html",
      })
      .state('state1.list', {
        url: "/list",
        templateUrl: "views/partials/state1.list.html",
        controller: function($scope) {
          $scope.items = ["A", "List", "Of", "Items"];
        }
      });
  });
Run Code Online (Sandbox Code Playgroud)

控制器:

angular.module('angularApp')
  .controller('RowsCtrl', ['$scope','$stateParams','$anchorScroll', '$location', 
    function ($scope, $stateParams, $anchorScroll, $location) {
    this.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];

    $scope.id = $stateParams.id;

    $scope.gotoRow = function(x) {
      var newHash = 'row' + x;
      if ($location.hash() !== newHash) {
        // set the $location.hash to `newHash` and
        // $anchorScroll will automatically scroll to it
        $location.hash('row' + x);
      } else {
        // call $anchorScroll() explicitly,
        // since $location.hash hasn't changed
        $anchorScroll();
      }
    };
  }]);
Run Code Online (Sandbox Code Playgroud)

它会完美地运作!我希望一切都清楚,你可以解决你的问题.