如果 URL 包含 x 的参数,如何在 AngularJS 中设置计时器以滚动到元素 ID?



如果URL包含参数,如何为AngularJS设置滚动到ID的计时器?顺便说一下,URL是外部的,因此它不是来自我的网站。

这是我的问题:

1.用户单击单词"查看今天的销售",网址为Outlook中电子邮件中的 www.mySite.com/#/index#today(强调它来自外部链接,因此我无法放置href等或编辑<a>标签,因为没有html/它是外部的。

2.当他们单击Outlook链接时,它会转到 www.mySite.com/#/index 并删除 #today。因此不会向下滚动到 #today 所在的位置。

3.当他们返回Outlook并再次单击链接时,#today 工作并且不会被删除。它还将向下滚动到它所在的位置。必须访问该站点才能正常工作。

我搜索了互联网,他们仍然没有任何外部链接的解决方案,我看到的是他们编辑<a>标签的站内解决方案。

我在下面尝试了这些,但没有一个有效:

索尔恩 1

*other routeProviders here*
...
$routeProvider.when('/index', {
templateUrl: 'app/views/index.htm'
});
$routeProvider.otherwise({ redirectTo: '/index#today' });

但是 # 只会变成 %23 或删除

索恩 2

我也尝试过这个滚动到:

app.directive('scrollto',
function ($anchorScroll, $location) {
return {
link: function (scope, element, attrs) {
element.click(function (e) {
e.preventDefault();
$location.hash(attrs["scrollto"]);
$anchorScroll();
});
}
};
})

并将 Outlook 中的链接更改为 www.mySite.com/#/index?scrollTo=today 但忘记了 scrollTo 是一个属性,因此它应该放在<a>标签中,对吗?但是我们使用外部链接,因此除了添加链接功能外,我们无法在 Outlook 中编辑任何内容。

索恩 3

最后我也尝试了这个:

...
$routeProvider.when('/index', {
controller: 'myCtrl',
templateUrl: 'app/views/index.htm'
});
...
app.run(function ($rootScope, $location, $anchorScroll, $timeout) {
$rootScope.$on("$routeChangeSuccess", function (event, next, current) {
if ($location.hash()) {
$timeout(function () { $anchorScroll() }, 5);
} else {
window.scrollTo(0, 0);
}
});
});
app.controller('myCtrl', ['$scope', '$location', '$anchorScroll',
function ($scope, $location, $anchorScroll) {
$scope.gotoBottom = function () {
$location.hash('today');
$anchorScroll();
};
}]);

但它不起作用。(还是一样,还是需要双击(

成为索恩4

所以我想也许我可以:

  1. 在 Outlook 链接中手动放置参数:example: www.mySite.com/#/index?scrollMe=today

  2. 检索在 url 框中手动键入
  3. 或在 outlook 电子邮件的 url 中手动键入的参数。

  4. 然后可以添加一个计时器,例如 2 秒或 1 秒,以滚动到页面加载后的参数 ID。

计时器的目的是自动滚动可能不起作用,因为页面尚未加载并且已经在滚动?可能不是,但我想确定计时器部分,所以我至少在滚动之前会让它等待一秒钟。我认为一秒钟不会伤害任何人。我也可以将其降低到毫秒,但计时器仅用于测试。

我真的是AngularJS的新手,我真的很想问你们,前辈和专家,是否有任何解决方法。 :(

干杯!

你可以使用$routeParams所以它会是这样的——

$routeProvider.when('/index/:when', {
controller: 'myCtrl',
templateUrl: 'app/views/index.html'
});
app.controller('myCtrl', ['$scope', '$routeParams', '$location', '$anchorScroll'
function ($scope, $routeParams, $location, $anchorScroll) {
var goToId = $routeParams.when;
$location.hash(goToId);
$anchorScroll();
}]);

我的索引.html有这个

<div id="today" style="margin-top: 2000px;">
This div shows today's contents
</div>

最后,网址应该是这样的/#/index/today/#/index/yesterday

AngularJS 文档供参考 - https://docs.angularjs.org/tutorial/step_09

最新更新