How to Use AngularJS to create a single-page application
This article describes how to use AngularJS to create a single-page application. AngularJS is a popular JavaScript library. For more information, see
Overview
Single-page applications are becoming increasingly popular. Websites that simulate single-page app behavior can provide the feeling of mobile phone/tablet apps. Angular helps us easily create such applications
Simple Application
We plan to create a simple application involving the home page, about and contact us page. Although Angular was created to create more complex applications than this, this tutorial shows the concepts we need in large projects.
Target
Single-page application
Refreshing new page changes
Each page contains different data
Although Javascript and Ajax can be used to implement the above functions, Angular can make processing easier in our applications.
Document Structure
-Script. js
-Index.html
-Pages
----- Home.html
----- About.html
----- Contact.html
HTML page
This part is relatively simple. We use Bootstrap and Font Awesome. Open your index.html file, and use the navigation bar to add a simple layout.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
<! -- 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 via CDN --> <Script src = "https://ajax.googleapis.com/ajax/libs/angularjs/1.0.8/angular.min.js"> </script> <Script src = "script. js"> </script> </Head> <Body> <! -- Header and navbar --> <Header> <Nav class = "navbar-default"> <Div class = "container"> <Div class = "navbar-header"> <A class = "navbar-brand" href = "/"> Angular Routing Example </a> </Div> <Ul class = "nav navbar-right"> <Li> <a href = "#"> <I class = "fa-home"> </I> Home </a> </li> <Li> <a href = "# about"> <I class = "fa-shield"> </I> About </a> </li> <Li> <a href = "# contact"> <I class = "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> <! -- FOOTER --> <Footer class = "text-center"> View the tutorial on <a href = "http://scotch.io/tutorials/angular-routing-and-templating-tutorial"> Scotch. io </a> </Footer> </Body> </Html> |
In the page hyperlink, we use "#". We do not want the browser to think that we are chained to about.html and contact.html.
Angular Application
Model and Controller
Now we are ready to set up our application. Let's first create an angular model and controller. For more information about models and controllers, see the documentation.
First, we need to use javascript to create our model and controller. We will put this operation in script. js:
?
1 2 3 4 5 6 7 8 9 10 11 |
// 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! '; }); |
Next, let's add the model and controller to our HTML page, so Angular can know how to guide our application. To test the effectiveness of the function, we will also display the value of $ scope. message, a variable we created.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<! -- 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.10/angular.min.js"> </script> <Script src = "// ajax.googleapis.com/ajax/libs/angularjs/1.2.10/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> |
In the div layer of main, we can now see the message we created. Knowing that our model and controller settings are complete and Angular can run properly, we will start to use this layer to display different pages.
Inject pages into the main layout
Ng-view is an angular command used to contain the template of the current route (/home,/about, or/contact). It will upload a file based on a specific path and bring it to the main layout (index.html ).
We will want to add the ng-view code to the website in div # main to tell Angular where to place the rendered page.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<! -- 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
Because we are creating a single-page application and do not want to refresh the page, we will use the Angular Routing Capability.
Let's take a look at our Angular file and add it to our application. We will use $ routeProvider in Angular to process our routes. In this way, Angular will process all the magical requests by acquiring a new file and injecting it into our layout.
AngularJS 1.2 and Routing
After version 1.1.6, The ngRoute model is not included in Angular. You need to declare the model at the beginning of the document to use it. This tutorial has been updated for AngularJS1.2:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
// Script. js // Create the module and name it scotchApp // Also include ngRoute for all our routing needs Var scotchApp = angular. module ('scotchapp', ['ngroup']); // 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 route through $ routeProvider. Through configuration, you will find that you can use the specified route, template file, or controller. In this way, each part of our application uses Angular controller and its own view.
Clear URL: angular places a well number in the URL by default. To avoid this, we need to use $ locationProvider to enable the HTML History API. It will remove the hash and create a beautiful URL. Our home page will pull the home.html file. the About and contact pages will pull their associated files. now, if we view our application and click the navigation bar, our content will change according to our meaning.
To complete this tutorial, we only need to define the page that will be injected. We will also let each of them display messages from their controllers.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<! -- Home.html --> <Div class = "jumbotron text-center"> <H1> Home Page <P >{{ message }}</p> </Div> <! -- About.html --> <Div class = "jumbotron text-center"> <H1> About Page <P >{{ message }}</p> </Div> <! -- Contact.html --> <Div class = "jumbotron text-center"> <H1> Contact Page <P >{{ message }}</p> </Div> |
Local running: Angular routing will only take effect after the environment you set for it. Make sure that http: // localhost is used or a type of environment. Otherwise, angular will say that cross-origin requests support HTTP.
Angular application Animation
Once you have completed all the routes, you can start playing with your site and add animations to it. therefore, you need to use the ngAnimate module provided by angular. later, you can use CSS animation to switch views in an animation mode.
SEO on a single page App
Ideally, this technology may be used in applications with user logon. Of course, you will not really want the pages of specific users to be indexed by search engines. For example, you will not want your reader account, Facebook login page, or Blog CMS page to be indexed.
If you do perform SEO for your applications, how can SEO take effect on applications/sites that use js to build pages? It is difficult for search engines to process these applications because the content is dynamically built by browsers and invisible to crawlers.
Make your application SEO friendly
The SEO-friendly technologies of js single-page applications need to be regularly maintained. According to official Google recommendations, You Need To Create HTML snapshots. The following is an overview of how they work:
Crawlers will find a friendly URL (http://scotch.io/seofriendly#key=value)
Then the crawler will want the content of the URL requested by the server (in a special way modified)
The Web server uses an HTML snapshot to return content.
HTML snapshots are processed by crawlers.
Then the search result will display the original URL