使用角度js路由单页应用程序

时间:2014-11-02 21:36:58

标签: angularjs url-routing single-page-application

我正在使用AngularJS构建一个Web单页面应用程序。我需要在没有http请求的客户端浏览器中单击链接更改URI。

http://example.com/ --->它显示我的单页应用程序并单击特定链接我需要的URL是http://example.com/about但没有发送http请求并显示隐藏的div。

2 个答案:

答案 0 :(得分:1)

我不知道你究竟想做什么,但如果你只想做一个http请求,你可以使用angular ui router之类的东西

$stateProvider
.state('main', {
  url: "/",
  templateUrl: "main.html"
})
.state('about', {
  url: "/about",
  templateUrl: "main.html",
  controller: function($scope) {
    $scope.showDiv = "true";
  }
})

这样你可以切换状态,因为你需要的所有东西都已加载,所以不再有任何东西被加载。或者您也可以使用parameters

但是为什么有一个额外的请求是如此糟糕?这将是一件有趣的事情! :)

编辑:使用$ location 的简单方法 (https://docs.angularjs.org/guide/的$ location)

的index.html:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example</title>
    <base href="/">
    <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.1/angular.min.js"></script>
    <script src="app.js"></script>
</head>
<body ng-app="html5-mode">
    <div ng-controller="LocationController">
        <button ng-click="changeUrl()">Change url</button>
    </div>
</body>
</html>

app.js:

angular.module('html5-mode', []) 
.controller("LocationController", function ($scope, $location) {
    $scope.$location = {};
    $scope.changeUrl = function () {
        // https://docs.angularjs.org/guide/$location
        console.log("The current path: " + $location.path());
        console.log("Changing url...");
        $location.path('/newValue')
    };
})
.config(function ($locationProvider) {
    $locationProvider.html5Mode(true).hashPrefix('!');
})

请务必将basePath设置为正确。

答案 1 :(得分:0)

看看html2js。将html模板转换为预先缓存的js文件是一项艰巨的任务。

理想情况下,您可以将此作为构建过程的一部分运行。同样,您可以运行监视任务,以便在保存模板时将HTML模板编译到预缓存中 - 这对开发很有用。

如果您已经使用了gulp,那么您可以使用package。 html2js有很多替代方法可以做同样的事情。因此,如果它不适合您的需求,请尝试另一个。

因此,当您导航到另一个页面时,HTML模板将被拉出角度缓存,而不是从服务器中获取。

相关问题