angularjs路由_具有AngularJS路由和模板的单页应用

angularjs路由

总览 (Overview)

Single page apps are becoming increasingly popular. Sites that mimic the single page app behavior are able to provide the feel of a phone/tablet application. Angular helps to create applications like this easily.

单页应用程序变得越来越流行。 模仿单页应用程序行为的网站能够提供电话/平板电脑应用程序的感觉。 Angular有助于轻松创建类似这样的应用程序。

我们的简单应用 (Our Simple App)

We're just going to make a simple site with a home, about, and contact page. Angular is built for much more advanced applications than this, but this tutorial will show many of the concepts needed for those larger projects.

我们将创建一个带有主页,关于和联系页面的简单站点。 Angular是为比此更高级的应用程序而构建的,但是本教程将展示那些较大的项目所需的许多概念。

目标 (Goals)

  • Single page application

    单页申请
  • No page refresh on page change

    页面更改时无页面刷新
  • Different data on each page

    每页上的数据不同
While this can be done with just Javascript and AJAX calls, Angular will make this process easier as our app starts growing. 尽管可以仅使用Javascript和AJAX调用来完成此操作,但随着我们的应用开始增长,Angular将使此过程变得更加容易。

档案结构 (File Structure)

- script.js             <!-- stores all our angular code -->
    - index.html            <!-- main layout -->
    - pages                 <!-- the pages that will be injected into the main layout -->
    ----- home.html
    ----- about.html
    ----- contact.html

HTML (HTML)

This is the simple part. We're using Bootstrap and Font Awesome. Open up your index.html file and we'll add a simple layout with a navigation bar.

这是简单的部分。 我们正在使用BootstrapFont Awesome 。 打开您的index.html文件,我们将添加带有导航栏的简单布局。

<!-- index.html -->
    <!DOCTYPE html>
    <html>
    <head>
      <!-- SCROLLS -->
      <!-- load bootstrap and fontawesome via CDN -->
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

      <!-- SPELLS -->
      <!-- load angular and angular route via CDN -->
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="script.js"></script>
    </head>
    <body>

        <!-- HEADER AND NAVBAR -->
        <header>
            <nav class="navbar navbar-default">
            <div class="container">
                <div class="navbar-header">
                    <a class="navbar-brand" href="/">Angular Routing Example</a>
                </div>

                <ul class="nav navbar-nav navbar-right">
                    <li><a href="#"><i class="fa fa-home"></i> Home</a></li>
                    <li><a href="#about"><i class="fa fa-shield"></i> About</a></li>
                    <li><a href="#contact"><i class="fa fa-comment"></i> Contact</a></li>
                </ul>
            </div>
            </nav>
        </header>

        <!-- MAIN CONTENT AND INJECTED VIEWS -->
        <div id="main">

            <!-- angular templating -->
            <!-- this is where content will be injected -->

        </div>

    </body>
    </html>

For linking to pages, we'll use the #. We don't want the browser to think we are actually travelling to about.html or contact.html.

要链接到页面,我们将使用# 。 我们不希望浏览器认为我们实际上正在访问about.htmlcontact.html

角度应用 (Angular Application)

模块和控制器 (Module and Controller)

We're going to setup our application. Let's create the angular module and controller. Check out the docs for more information on each.

我们将设置我们的应用程序。 让我们创建角度模块控制器 。 查看文档以获取有关每个文档的更多信息。

First, we have to create our module and controller in javascript. We will do that now in script.js.

首先,我们必须使用javascript创建模块和控制器。 我们现在将在script.js

// script.js

    // create the module and name it scotchApp
    var scotchApp = angular.module('scotchApp', []);

    // create the controller and inject Angular's $scope
    scotchApp.controller('mainController', function($scope) {

        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';
    });

Let's add the module and controller to our HTML so that Angular knows how to bootstrap our application. To test that everything is working, we will also show the $scope.message variable that we created.

让我们将模块和控制器添加到HTML中,以便Angular知道如何引导我们的应用程序。 为了测试一切正常,我们还将显示我们创建的$scope.message变量。

<!-- index.html -->
    <!DOCTYPE html>

    <!-- define angular app -->
    <html ng-app="scotchApp">
    <head>
      <!-- SCROLLS -->
      <!-- load bootstrap and fontawesome via CDN -->
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" />
      <link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.0/css/font-awesome.css" />

      <!-- SPELLS -->
      <!-- load angular via CDN -->
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular.min.js"></script>
          <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.25/angular-route.js"></script>
      <script src="script.js"></script>
    </head>

    <!-- define angular controller -->
    <body ng-controller="mainController">

    ...

    <!-- MAIN CONTENT AND INJECTED VIEWS -->
    <div id="main">
        {{ message }}

        <!-- angular templating -->
        <!-- this is where content will be injected -->
    </div>

Inside of our main div, we will now see the message that we created. Since we have our module and controller set up and we know that Angular is working properly, we will start working on using this layout to show the different pages.

在我们的main div内部,我们现在将看到我们创建的消息。 由于我们已经设置了模块和控制器,并且知道Angular运行正常,因此我们将开始使用此布局来显示不同的页面。

将页面注入主布局 (Injecting Pages into the Main Layout)

ng-view is an Angular directive that will include the template of the current route (/home, /about, or /contact) in the main layout file. In plain words, it takes the file we want based on the route and injects it into our main layout (index.html).

ng-view是一个Angular指令,它将在主布局文件中包含当前路线(/ home,/ about或/ contact)的模板。 简而言之,它根据路线获取我们想要的文件,并将其注入到我们的主布局( index.html )中。

We will add the ng-view code to our site in the div#main to tell Angular where to place our rendered pages.

我们将在div#main中的站点中添加ng-view代码,以告诉Angular将渲染页面放置在何处。

<!-- index.html -->
    ...

    <!-- MAIN CONTENT AND INJECTED VIEWS -->
    <div id="main">

        <!-- angular templating -->
        <!-- this is where content will be injected -->
        <div ng-view></div>

    </div>

    ...

配置路线和视图 (Configure Routes and Views)

Since we are making a single page application and we don't want any page refreshes, we'll use Angular's routing capabilities.

由于我们正在制作单个页面应用程序,并且我们不希望任何页面刷新,因此我们将使用Angular的路由功能。

Let's look in our Angular file and add to our application. We will be using $routeProvider in Angular to handle our routing. This way, Angular will handle all of the magic required to go get a new file and inject it into our layout.

让我们看一下Angular文件并添加到我们的应用程序中。 我们将在Angular中使用$ routeProvider来处理路由。 这样,Angular将处理获取新文件并将其注入到我们的布局中所需的所有魔术。

AngularJS 1.2 and Routing The ngRoute module is no longer included in Angular after version 1.1.6. You will need to call the module and add it to the head of your document to use it. This tutorial has been updated for AngularJS 1.2和路由 1.1.6版本之后,Angular不再包含ngRoute模块。 您将需要调用该模块并将其添加到文档的开头以使用它。 本教程已针对 AngularJS 1.2 AngularJS 1.2更新
// script.js

    // create the module and name it scotchApp
        // also include ngRoute for all our routing needs
    var scotchApp = angular.module('scotchApp', ['ngRoute']);

    // configure our routes
    scotchApp.config(function($routeProvider) {
        $routeProvider

            // route for the home page
            .when('/', {
                templateUrl : 'pages/home.html',
                controller  : 'mainController'
            })

            // route for the about page
            .when('/about', {
                templateUrl : 'pages/about.html',
                controller  : 'aboutController'
            })

            // route for the contact page
            .when('/contact', {
                templateUrl : 'pages/contact.html',
                controller  : 'contactController'
            });
    });

    // create the controller and inject Angular's $scope
    scotchApp.controller('mainController', function($scope) {
        // create a message to display in our view
        $scope.message = 'Everyone come and see how good I look!';
    });

    scotchApp.controller('aboutController', function($scope) {
        $scope.message = 'Look! I am an about page.';
    });

    scotchApp.controller('contactController', function($scope) {
        $scope.message = 'Contact us! JK. This is just a demo.';
    });

Now we have defined our routes with $routeProvider. As you can see by the configuration, you can specify the route, the template file to use, and even a controller. This way, each part of our application will use its own view and Angular controller.

现在,我们使用$ routeProvider定义了路由。 从配置中可以看到,您可以指定路由 ,要使用的模板文件,甚至是控制器 。 这样,我们应用程序的每个部分都将使用其自己的视图和Angular控制器。

Clean URLs: By default, Angular will throw a hash (#) into the URL. To get rid of this, we will need to use 干净的URL :默认情况下,Angular会将哈希(#)放入URL。 要摆脱这种情况,我们将需要使用 $locationProvider to enable the HTML History API. This will remove the hash and make pretty URLs. For more information: $locationProvider启用HTML History API。 这将删除哈希并生成漂亮的URL。 有关更多信息: Pretty URLs in AngularJS: Removing the #. AngularJS中的漂亮URL:删除#

Our home page will pull the home.html file. About and contact will pull their respective files. Now if we view our app, and click through the navigation, our content will change just how we wanted.

我们的主页将拉出home.html文件。 关于和联系将拉出他们各自的文件。 现在,如果我们查看我们的应用程序,然后单击导航,我们的内容将发生改变。

To finish off this tutorial, we just need to define the pages that will be injected. We will also have them each display a message from its respectiive controller.

要结束本教程,我们只需要定义将要注入的页面。 我们还将让它们各自显示来自其相应控制器的消息。

<!-- home.html -->
    <div class="jumbotron text-center">
        <h1>Home Page</h1>

        <p>{{ message }}</p>
    </div>
<!-- about.html -->
    <div class="jumbotron text-center">
        <h1>About Page</h1>

        <p>{{ message }}</p>
    </div>
<!-- contact.html -->
    <div class="jumbotron text-center">
        <h1>Contact Page</h1>

        <p>{{ message }}</p>
    </div>
Working Locally: Angular routing will only work if you have an environment set for it. Make sure you are using 本地工作 :只有在设置了环境的情况下,角路由才会起作用。 确保您使用的是 http://localhost or some sort of environment. Otherwise Angular will spit out a http://localhost或某种环境。 否则,Angular将吐出 Cross origin requests are only supported for HTTP. Cross原点请求仅支持HTTP

动画Angular应用 (Animating Angular Apps)

Once you have all the routing done, you can start to get really fancy with your site and add in animations. To do this, you will need the ngAnimate module provided by Angular. After that you can animate your pages into view with CSS animations.

完成所有路由后,您就可以开始真正了解您的站点并添加动画了。 为此,您将需要Angular提供的ngAnimate模块。 之后,您可以使用CSS动画对页面进行动画处理。

For a tutorial on how to get animations in your site, read: Animating AngularJS Apps: ngView.

有关如何在您的网站中获取动画的教程,请阅读: AngularJS应用动画:ngView

单页应用程序上的SEO (SEO on Single Page Apps)

Ideally, this technique would be used for an application after a person has signed in. You wouldn't really want those pages indexed since they are personalized to that specific user. For example, you wouldn't want your Reader account, Facebook logged in pages, or Blog CMS pages indexed.

理想情况下,此技术将在一个人登录后用于应用​​程序。由于这些页面是针对该特定用户的个性化的,因此您实际上并不需要索引这些页面。 例如,您不希望索引您的读者帐户,Facebook登录页面或Blog CMS页面。

If you did want SEO for you application though, how does SEO work for applications/sites that get their pages built with Javascript? Search engines have a difficult time processing these applications because the content is built dynamically by the browser and not visible to crawlers.

如果您确实希望为您的应用程序提供SEO,那么SEO如何用于使用Java构建其页面的应用程序/站点? 搜索引擎很难处理这些应用程序,因为内容是由浏览器动态构建的,并且对于爬网程序不可见。

使您的应用SEO友好 (Making Your App SEO Friendly)

Techniques to make Javascript single page applications SEO friendly require regular maintenance. According to the official Google suggestions, you would create HTML snapshots. The basic overview of how it would work is that:

使Javascript单页应用程序变得SEO友好的技术需要定期维护。 根据Google的官方建议 ,您将创建HTML快照。 其工作原理的基本概述是:

  1. A crawler would find a pretty URL (https://scotch.io/seofriendly#key=value)

    搜寻器会找到漂亮的URL( https://scotch.io/seofriendly#key=value
  2. The crawler would then ask the server for the contents of this URL (in a special modified way)

    然后,搜寻器会向服务器询问此URL的内容(以一种特殊的修改方式)
  3. Web server returns content using an HTML snapshot

    Web服务器使用HTML快照返回内容
  4. HTML snapshot is processed by the crawler

    HTML快照由搜寻器处理
  5. Search results then show the original URL

    搜索结果然后显示原始URL

For more information on this process, be sure to look at Google's AJAX Crawling and their guide on creating HTML snapshots.

有关此过程的更多信息,请务必查看Google的AJAX爬行及其有关创建HTML快照的指南。

SEO Article: We've written up a tutorial on how to make Angular SEO friendly. Give it a read if you're interested: SEO文章 :我们已经编写了有关如何使Angular SEO友好的教程。 如果您有兴趣请阅读: AngularJS SEO with Prerender.io. AngularJS SEO与Prerender.io

结论 (Conclusion)

This was a very simple tutorial on how to get Angular routing to work with a layout and separate views. Now you can go ahead and create larger single page applications. There is much more to learn with Angular and I'll keep writing about different features along my learning journey of Angular.

这是一个非常简单的教程,说明如何使Angular路由与布局和单独的视图一起使用。 现在,您可以继续创建更大的单页应用程序。 使用Angular还有很多要学习的东西,在Angular的学习过程中,我将继续撰写有关不同功能的文章。

If anyone has any suggestions for future Angular articles or different ways to do what we've just done here (there are so many ways to write the same thing, it can drive a person insane), sound off in the comments.

如果有人对未来的Angular文章有任何建议,或者有其他方法可以完成我们刚刚在这里所做的事情(有很多方法可以写相同的东西,这可能会使人发疯),请在评论中取消。

进一步阅读如果您想在路由方面寻求更大的灵活性,例如嵌套视图和基于状态的模板而不是基于路由,那么您一定会感兴趣 (Further Reading If you are looking for more flexibility in routing like nested views and state based templating instead of route based, then you'll definitely be interested in)

UI Router. For an article on UI Router: AngularJS Routing Using UI-Router

UI路由器 。 有关UI路由器的文章: 使用UI-Router进行AngularJS路由

Edit: Added information on SEO for using this technique. 编辑:添加了有关使用此技术的SEO的信息。 Edit: Updated article for AngularJS 1.2 编辑: AngularJS 1.2的更新的文章

翻译自: https://scotch.io/tutorials/single-page-apps-with-angularjs-routing-and-templating

angularjs路由

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值