Programming guidelines for creating single page applications using AngularJS

  • 2020-06-19 09:42:16
  • OfStack

An overview of the

Single-page apps are becoming more and more popular. Any site that simulates the behavior of a one-page app can provide the feel of a phone/tablet app. Angular can help us create such applications easily
Simple application

We are going to create a simple application that involves the home page, about and contact us page. While Angular is designed to create more complex applications than this, this tutorial demonstrates many of the concepts we need in large projects.
The target

A single page application No refresh page changes Each page contains different data

While Javascript and Ajax do this, in our case, Angular makes it easier to handle.
The document 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 page

This part is easier. We use Bootstrap and Font Awesome. Open your ES40en.html file, then we'll use the navigation bar to add a simple layout.


<!-- 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 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>
 
  <!-- 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 page hyperlinks, we use "#". We don't want the browser to think we're actually linking to about.html and contact.html.
Angular application
Model and controller

Now we're ready to set up our application. Let's start by creating the angular model and controller. Refer to the documentation for models and controllers for more information.

First, we need to use javascript to create our model and controller, which we put into ES60en.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 model and controller to our HTML page so that Angular knows how to guide our application. To test the validity of the function, we will also show the value of a variable we created, $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.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 main, the div layer, we can now see the message we created. Now that our model and controller are set up and Angular is up and running, we'll start using this layer to display different pages.

Inject the page into the main layout

ng-view is an angular instruction that contains the template for the current route (/home, /about, or /contact), which takes the file based on the specific route and puts it such as into the main layout (ES90en.html).

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


<!-- 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 creating a single page application and do not want the page to refresh, 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 handle our routing. In this way, Angular will handle all the magic requests by taking a new file and injecting it into our layout.

AngularJS 1.2 and routing

After version 1.1.6, the ngRoute model is no longer included in Angular. You need to use the model by declaring it at the beginning of the document. This tutorial has been updated for AngularJS1.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.';
});

We have now defined our route through $routeProvider. You can find out by configuration that you can use the specified routes, template files, and even controllers. In this way, each part of our application USES the Angular controller and its own view.


Cleaning URL: By default, angular puts 1 well number into URL. To avoid this, we need to use $locationProvider to enable HTML History API. It will remove hash and create a beautiful URL. Our home page will pull up the home.html file. The About and contact pages will pull up their associated files. Now if we look at our application and click on the navigation, our content will change as we mean it.

To complete the tutorial, we just need to define the pages that will be injected, and we'll have each of them display a message from their associated 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>

Run locally: The Angular route only works after you set up the environment for it. Make sure you are using http://localhost or some type of environment, otherwise angular will say that cross-domain requests support HTTP.

Animation of Angular application

Once you have all the routes complete, you can start to play with your site and animate it. To do this, you need to use the ngAnimate module provided by angular. You can then animate the views using CSS animations.
SEO on single page App

Ideally, this technique might be used in applications that have a user logged in. You certainly don't want pages that are private to a particular user to be indexed by the search engines. For example, you don't want your reader account, Facebook login page or CMS blog page to be indexed.

If you do want to use SEO for your application, how do you get SEO to work on applications/sites that use js to build pages? Search engines struggle to process these applications because the content is built dynamically by the browser and is invisible to crawlers.

Make your app SEO friendly

The technology that makes js single-page applications SEO-friendly requires regular maintenance. According to the official Google recommendation, you need to create snapshots of HTML. Here's an overview of how it works:

The crawler will find a friendly URL (http: / / scotch io/seofriendly # key = value) Then the crawler will request the contents of this URL to the server (in a special modified way) The Web server returns the contents using 1 HTML snapshot The HTML snapshot is processed by the crawler The search results then show the original URL

For more information on this process, check out Google's AJAX crawler and their guide to creating HTML snapshots.


Related articles: