angularjs -在一定时间限制后切换页面

AngularJS-Switching between Pages after Certain Time Limit

本文关键字:换页 定时间 angularjs      更新时间:2023-09-26

我已经在StackOverflow周围搜索了,但我无法找到我正在寻找的适当解决方案,所以我会再次问这个问题。我正在尝试创建一个应用程序,它以一个带有一些很酷的图片等的"启动页面"开始,但在一定时间(比如4秒)后,它将过渡到下一个页面。我该怎么做呢?我读了一些关于timeout()函数的资料,但还是不能真正理解它。

我在考虑某种计时功能,当时间到期时,它激活ui-sref或href转到下一页。顺便说一下,我是一个AngularJS新手,所以请不要评判:)如果你想让我发布一些代码,我可以这样做,但我真的不知道从哪里开始…只要在两个页面上都有一些模板就可以了。

如果你在启动页面的控制器中注入$state和$timeout,你就可以拥有一个函数。

function activate (){
  $timeout(function(){
    $state.go('page2')
  },4000)
}
activate();

你也可以没有重定向,而是在你的主页上弹出一个4秒后消失,这样你就不需要重定向,但我不知道你的应用程序是如何设计的。

这是假设你已经设置了一些路由

我在考虑某种计时功能,当时间到期时,它激活ui-sref或href转到下一页。

这就是$timeout()。当您向它传递一个函数和一个超时(以毫秒为单位)时,它将在指定的毫秒数过去后运行该函数。

$timeout(function() {
    $state.go('page2');
}, 4000);

将在4秒(4000ms)超时后调用该函数(转到page2)。$timeout()之后的代码行将立即执行(即不等待超时)。

你可以把这段代码放在你的启动页面的控制器的开始。确保你已经注入了$state和$timeout。

下面是一个简单的Angular应用程序,它可以满足你的需求。请记住,我使用的是routeProvider模块,而不是stateProvider模块,但原理是一样的。

我已经为你准备了一个实时的Plunker演示。有关如何使用$timeout的更多信息,请单击这里。

相关部分为:

app.controller('MainCtrl', function($scope, $timeout, $location) {
  // Main controller
  $scope.title = "First Page";
  var goToSecondPage = function() {
    $location.path('/second');
  };
  $timeout(goToSecondPage, 5000);
});

app.js

var app = angular.module('plunker', ['ngRoute']);
app.controller('MainCtrl', function($scope, $timeout, $location) {
  // Main controller
  $scope.title = "First Page";
  var goToSecondPage = function() {
    $location.path('/second');
  };
  $timeout(goToSecondPage, 5000);
});
app.controller('SecondCtrl', function($scope, $timeout, $location) {
  // Second controller
  $scope.title = "Second Page";
  var goToMainPage = function() {
    $location.path('/');
  };
  $timeout(goToMainPage, 5000);
});
app.config(['$routeProvider', function($routeProvider) {
    $routeProvider
        .when('/', {
            templateUrl: "main.tpl.html",
            controller: 'MainCtrl'
        })
        .when('/second', {
            templateUrl: "second.tpl.html",
            controller: 'SecondCtrl'
        })
        .otherwise({ redirectTo: '/' });
}]);

index . html

<!DOCTYPE html>
<html ng-app="plunker">
  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.4.x" src="https://code.angularjs.org/1.4.9/angular.js" data-semver="1.4.9"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.9/angular-route.js"></script>
    <script src="app.js"></script>
  </head>
  <body>
    <h1>My Angular App</h1>
    <ng-view></ng-view>
  </body>
</html>

main.tpl.html

<h2>{{title}}</h2>
<p>You will be redirected to the second page in 5 seconds...</p>

second.tpl.html

<h2>{{title}}</h2>
<p>This is the second page.</p>
<p>You will be redirected to the main page in 5 seconds...</p>