如何创建不使用路由的 AngularJS SPA 应用程序? [英] How can I create an AngularJS SPA application that does not use routing?

查看:21
本文介绍了如何创建不使用路由的 AngularJS SPA 应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个 AngularJS 应用程序,它只使用一个 HTTP 域,在 .com 之后没有任何内容.例如一个应用程序,它是浏览器中显示的唯一 URL:

www.myapp.com

这可能吗,我需要做什么?到目前为止,我看到的所有应用程序都使用类似的东西:

www.myapp.com/userswww.myapp.com/screen1

解决方案

好的;您所需要的只是某种顶级应用程序状态和响应该状态的 UI.这就是 ngRoute 在幕后的全部内容——状态就在地址栏中,如何响应该状态的配置位于 $routeProvider(即,反过来,通过 ngView 指令在 DOM 中实现).

考虑这个简单的例子:

<h1>某些页面</h1><ul><li><a href='' ng-click='setPage("page1")'>第 1 页</a></li><li><a href='' ng-click='setPage("page2")'>第 2 页</a></li><li><a href='' ng-click='setPage("page3")'>第 3 页</a></li><div ng-include="page + '.html'"></div>

app.controller('ApplicationController', function($scope) {$scope.page = 'page1';$scope.setPage = 函数(pg){$scope.page = pg;}});

您可以在此处查看在 Plunker 中的工作情况:http://plnkr.co/edit/hpnGtMkV6V4JtPRrQmes?p=preview

点击全屏按钮,您就可以看到地址栏(以及它不会改变的事实).

<小时>

如果不将您的应用程序状态存储在地址栏中,用户就无法轻松地在您的应用程序中为他们的位置添加书签或使用浏览器的按钮前进/后退,这是毫无价值的.仔细考虑您正在构建的应用是否会受益于这种限制.

I would like to create an AngularJS application that's uses just the one HTTP domain with nothing after the .com. For example an application where this is the only URL that displays in the browser:

www.myapp.com

Is this possible and what would I need to do this? All of the applications I have seen so far use something like:

www.myapp.com/users
www.myapp.com/screen1

etc.

解决方案

Sure; all you need is some kind of top-level application state and UI that responds to that state. That's all ngRoute is, under the hood--the state just lives in your address bar, and the configuration for how to respond to that state lives in $routeProvider (which is, in turn, realized in the DOM via the ngView directive).

Consider this simple example:

<div ng-controller="ApplicationController">
  <h1>Some Pages</h1>
  <ul>
    <li><a href='' ng-click='setPage("page1")'>Page 1</a></li>
    <li><a href='' ng-click='setPage("page2")'>Page 2</a></li>
    <li><a href='' ng-click='setPage("page3")'>Page 3</a></li>
  </ul>

  <div ng-include="page + '.html'"></div>
</div>

app.controller('ApplicationController', function($scope) {
  $scope.page = 'page1';

  $scope.setPage = function(pg) {
    $scope.page = pg;
  }
});

You can see this working in a Plunker here: http://plnkr.co/edit/hpnGtMkV6V4JtPRrQmes?p=preview

Click the full screen button so you can see the address bar (and the fact that it doesn't change).


It is worth nothing that, without storing your application state in the address bar, users don't have a very easy way of bookmarking their place in your app or going forward/back using their browser's buttons. Carefully consider whether you're building an app that would benefit from this kind of limitation.

这篇关于如何创建不使用路由的 AngularJS SPA 应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆