Single Page Application using AngularJs Tutorial

AngularJS-large
AngularJs is a powerful javascript framework for building dynamic web applications. It became insanely popular nowadays. The good thing about Angular is that it has a set of ready-to-use modules to simplify building of single page applications.

In this tutorial, we will show you how to build a simple single page application. Even though we will build a small app, you will learn the concepts and will be able to build larger apps.

Single Page Application

Single page application (SPA) is a web application that fits on a single page. All your code (JS, HTML, CSS) is retrieved with a single page load. And navigation between pages performed without refreshing the whole page.

ngspa_740_210

 

Pros

No page refresh

When you are using SPA, you don’t need to refresh the whole page, just load the part of the page which needs to be changed. Angular allows you to pre-load and cache all your pages, so you don’t need extra requests to download them.

Better user experience

SPA feels like a native application: fast and responsive.

Ability to work offline

Even if user loses internet connection, SPA can still work because all the pages are already loaded.

Cons

More complex to build

You need to write pretty much javascript, handle shared state between pages, manage permissions, etc.

SEO

To index your SPA app, search engine crawlers should be able to execute javascript. Only recently Google and Bing started indexing Ajax-based pages by executing JavaScript during crawling. You need to create static HTML snapshots specially for search engines.

Initial load is slow

SPA needs to download more resources when you open it.

Client should have javascript enabled

Of course, SPA requires javascript. But fortunately, almost everyone has javascript enabled.

Angular Application

Every angular application starts from creating a module. Module is a container for the different parts of your application: controllers, service, etc.

var app = angular.module('myApp', []);

Lets define a simple controller:

app.controller('HomeController', function($scope) {
  $scope.message = 'Hello from HomeController';
});

After we created module and controller, we need to use them in our HTML.

First of all, we need to include angular script and app.js that we built.

Then need to specify our module in ng-app attribute and controller in ng-controller attribute

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
  </head>
  <body ng-controller="HomeController">
    <h1>{{message}}</h1>
    <script src="app.js"></script>
  </body>
</html>

If you done this correctly, you should see:

1

Since we have our module and controller set up and we know that Angular is working properly, we will start working on adding single page application support.

ngRoute

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

We will use ngRoute module for that.

The ngRoute module provides routing, deeplinking services and directives for angular apps.

We need to include angular-route script after the main angular script.

경축! 아무것도 안하여 에스천사게임즈가 새로운 모습으로 재오픈 하였습니다.
어린이용이며, 설치가 필요없는 브라우저 게임입니다.
https://s1004games.com

<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>

Then we need to specify that our module depends on ngRoute module to be able to use it.

var app = angular.module('myApp', ['ngRoute']);

The next thing is to distinguish common HTML for every page. This HTML will be layout of the website.

Then we need to specify the place where HTML of each page will be placed in our layout. There is a ng-view directive for that.

ng-view is an Angular directive that will include the template of the current route (for example, /blog or /about) in the main layout file.

In plain words, it takes the file we specified for current route and injects it into the layout in the place of ng-view directive.

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
  </head>
  <body>

    <div ng-view></div>

    <script src="app.js"></script>
  </body>
</html>

When HTML is ready, we need to configure our routes. We will use $routeProvider service from the ngRoute module.

For each route, we need to specify templateUrl and controller.

If user will try to go to the route that does not exist, we can handle this by using otherwise function. In our case, we will redirect user to the “/” route:


var app = angular.module('myApp', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider

  .when('/', {
    templateUrl : 'pages/home.html',
    controller  : 'HomeController'
  })

  .when('/blog', {
    templateUrl : 'pages/blog.html',
    controller  : 'BlogController'
  })

  .when('/about', {
    templateUrl : 'pages/about.html',
    controller  : 'AboutController'
  })

  .otherwise({redirectTo: '/'});
});

Then we need to build controllers for every route (we already specified their names in routeProvider):


app.controller('HomeController', function($scope) {
  $scope.message = 'Hello from HomeController';
});

app.controller('BlogController', function($scope) {
  $scope.message = 'Hello from BlogController';
});

app.controller('AboutController', function($scope) {
  $scope.message = 'Hello from AboutController';
});

Our pages will be simple:

home.html

<h1>Home</h1>

<h3>{{message}}</h3>

blog.html

<h1>Blog</h1>

<h3>{{message}}</h3>

about.html

<h1>About</h1>

<h3>{{message}}</h3>

Note that we don’t need to use html, head, body tags in our page. This pages will always be used inside layout as partial HTML.

Lets add links that will switch our pages. The final HTML looks like this:

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
  </head>
  <body>
    <a href="#/">Home</a>
    <a href="#/blog">Blog</a>
    <a href="#/about">About</a>

    <div ng-view></div>

    <script src="app.js"></script>
  </body>
</html>

Browsers don’t support loading resources from disk using ajax, so you can use any HTTP server to serve static HTMLs.

python -m SimpleHTTPServer

If you don’t want to do this, you can include your partial HTMLs to index.html using script tag with type text/ng-template.

When angular see this templates, it will load its content to the template cache and will not perform ajax request to get their content.

<!doctype html>
<html ng-app="myApp">
  <head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.4.7/angular-route.min.js"></script>
  </head>
  <body>
    <script type="text/ng-template" id="pages/home.html">
      <h1>Home</h1>
      <h3>{{message}}</h3>
    </script>
    <script type="text/ng-template" id="pages/blog.html">
      <h1>Blog</h1>
      <h3>{{message}}</h3>
    </script>
    <script type="text/ng-template" id="pages/about.html">
      <h1>About</h1>
      <h3>{{message}}</h3>
    </script>

    <a href="#/">Home</a>
    <a href="#/blog">Blog</a>
    <a href="#/about">About</a>

    <div ng-view></div>

    <script src="app.js"></script>
  </body>
</html>

Conclusion

In this tutorial, you learned how to build a single page application using Angular. Now you can go ahead and create more complex single page apps.

Demo

http://plnkr.co/edit/ClBmOH3ljAWueRBdKGKR?p=preview

 

[출처] https://tests4geeks.com/single-page-application-using-angularjs-tutorial/

 

 

본 웹사이트는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 웹사이트 서버의 유지 및 관리, 그리고 기술 콘텐츠 향상을 위해 쓰여집니다.
번호 제목 글쓴이 날짜 조회 수
34 [javascript] React - Apache에 배포하기 file 졸리운_곰 2026.01.25 444
33 Python으로 GraphQL 서버 구현 file 졸리운_곰 2019.12.17 541
32 처음 만나는 GraphQL file 졸리운_곰 2019.12.17 371
31 웹팩(Webpack) 이란, 웹팩 간단 정리 및 리액트(React) 기본 개발환경 세팅. [2] file 졸리운_곰 2019.11.08 581
30 웹팩(Webpack) 이란, 웹팩 간단 정리 및 리액트(React) 기본 개발환경 세팅. [1] file 졸리운_곰 2019.11.08 411
29 PHP 로 css/js 보호하기 졸리운_곰 2019.11.08 437
28 Three.js를 이용한 WebGL: 기본 file 졸리운_곰 2019.11.08 495
27 underscore.js로 편해지자 졸리운_곰 2018.10.16 545
26 자바스크립트로 각종 값넘기는방법 졸리운_곰 2018.01.24 518
25 form 데이터 주고 받기 file 졸리운_곰 2018.01.24 489
24 Node.js & WebSocket — Simple chat tutorial file 졸리운_곰 2017.12.08 612
23 JavaScript 모듈화 도구, webpack file 졸리운_곰 2017.10.30 537
22 웹팩이란? 졸리운_곰 2017.10.30 531
21 이해하기 쉬운 Webpack 가이드 file 졸리운_곰 2017.10.30 853
20 [jquery] Ajax를 품은 jQuery file 졸리운_곰 2017.04.25 466
19 Create Your First Mobile App with AngularJS and Ionic file 졸리운_곰 2016.11.20 1269
» Single Page Application using AngularJs Tutorial file 졸리운_곰 2016.11.20 458
17 AngularJS Tutorial - Building a Web App in 5 minutes file 졸리운_곰 2016.11.20 460
16 자바스크립트의 'this' 키워드 이해하기 졸리운_곰 2016.11.17 634
15 jQuery 핵심 - 노드 다루기 졸리운_곰 2016.11.17 774
대표 김성준 주소 : 경기 용인 분당수지 U타워 등록번호 : 142-07-27414
통신판매업 신고 : 제2012-용인수지-0185호 출판업 신고 : 수지구청 제 123호 개인정보보호최고책임자 : 김성준 sjkim70@stechstar.com
대표전화 : 010-4589-2193 [fax] 02-6280-1294 COPYRIGHT(C) stechstar.com ALL RIGHTS RESERVED