Angularjs 如何使用angular ui router滚动到页面的某个区域?
我有一个网页,上面有一个网格表。当显示未单击行的网格时,状态为“home.pages”,页面URL显示以下内容:Angularjs 如何使用angular ui router滚动到页面的某个区域?,angularjs,angular-ui-router,Angularjs,Angular Ui Router,我有一个网页,上面有一个网格表。当显示未单击行的网格时,状态为“home.pages”,页面URL显示以下内容: http://localhost:1495/subjects/4/admin/words http://localhost:1495/subjects/4/admin/words/1234 当用户在网格中单击word 1234的行时,状态更改为“home.pages.page”,wordId参数为1234,URL显示如下: http://localhost:1495/subjec
http://localhost:1495/subjects/4/admin/words
http://localhost:1495/subjects/4/admin/words/1234
当用户在网格中单击word 1234的行时,状态更改为“home.pages.page”,wordId参数为1234,URL显示如下:
http://localhost:1495/subjects/4/admin/words
http://localhost:1495/subjects/4/admin/words/1234
当我使用angular ui router时,是否可以让页面滚动到wordId为1234的行 在Word页面的控制器中,您应该查看/words的$stateParams,然后根据它采取行动 我建议您将wordId添加为queryParam,而不是路径的一部分(如
http://localhost:1495/subjects/4/admin/words?wordId=1234
)
假设您的ui路由器配置中有类似的内容:
$stateProvider.state('subjects.admin.words', {
url: '?' + admin/words?wordId',
…
})
你可以这样做
$scope.$watch(
function () {
return $stateParams.wordId;
},
function (wordId) {
if (wordId) {
scrollTo(wordId);
}
}
);
function scrollTo(line) {
// scroll code
}
我想这就是你想要的:你可以使用服务滚动到页面的某个区域,无论你使用的是角度ui/ui路由器还是ng路由。您只需为行创建一个控制器,在这种特殊情况下,注入必要的服务,如:$scope、$stateParams、$anchorScroll、$location,并声明一个管理滚动逻辑的方法,例如: 模板:
<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>
控制器:
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();
}
};
}]);
它将完美地工作!我希望一切都清楚,您可以解决您的问题。路由器:
$stateProvider
.state('home.pages', {
url: 'pages/',
// Template, controller,...
});
.state('home.pages.page', {
url: 'page/:wordId',
// Template, controller,...
});
控制器(home.pages.page
):
你可以使用普通的html锚吗?@andrew.butkus-是的,我可以使用这些,但我不确定如何将它们与angular ui路由器状态集成。我希望能找到一些例子,作为我需要做什么的基础。也许在路线更改上设置一个手表,然后选择id,然后使用锚滚动滚动到路径上的id。您能选择正确的答案吗?