我正在尝试实现一个系统,在路线更改后,我只想运行一次基于动画的 JavaScript。发生的情况是,现在如果您在页面之间切换,然后返回到“关于”页面。这些脚本确实会减慢网站速度,这正是我试图避免的。
app.controller('aboutController', function($scope, $route) {
$scope.$on('$routeChangeSuccess', function() {
// Just need this to run once
$('#about').particleground({
dotColor: '#666',
lineColor: '#666',
lineWidth: .3,
particleRadius: 3,
parallaxMultiplier: 3
});
});
最佳答案
在 $routeChangeSuccess` 中运行动画之前检查 currentRoute.redirectTo
。它将防止动画多次运行。
$scope.$on("$routeChangeSuccess", function(event, currentRoute, previousRoute){
if(!currentRoute.redirectTo) {
$('#about').particleground({
dotColor: '#666',
lineColor: '#666',
lineWidth: .3,
particleRadius: 3,
parallaxMultiplier: 3
});
}
});
执行两次的原因是:
在 HTML 中:
<a href="#about">› About Me</a>
在 href 中,您只有 #about
,但它必须是 #/about
。
<a href="#/about">› About Me</a>
关于javascript - 路由更改后,运行一次js脚本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29454389/