Tạo Single Page Application -Angular

Hi all,
Hôm nay mình sẽ hướng dẫn các bạn tạo SPA với angular JS , cũng không có nhiều thời gian nên mình không đi vào nhiều chi tiết, mình tạo sẳn project trên github để các bạn tham khảo.
Trang tạo ra sẽ như dưới:(template mình copy trên mạng)


Đâu tiên mình sẽ nói về structure, bạn xem cấu trúc như dưới

.
└── ROOT
    ├── app.cfg.js
    ├── app.mdl.js
    ├── app.srv.js
    ├── assets
    │   ├── css
    │   │   ├── bootstrap.css
    │   │   └── bootstrap.css.map
    │   ├── fonts
    │   │   ├── glyphicons-halflings-regular.eot
    │   │   ├── glyphicons-halflings-regular.svg
    │   │   ├── glyphicons-halflings-regular.ttf
    │   │   ├── glyphicons-halflings-regular.woff
    │   │   └── glyphicons-halflings-regular.woff2
    │   └── js
    │       ├── angularJS
    │       │   ├── angular-cookies.js
    │       │   ├── angular.js
    │       │   ├── angular-resource.js
    │       │   ├── angular-route.js
    │       │   └── angular-sanitize.js
    │       ├── angular-ui-router.js
    │       ├── bootstrap.js
    │       ├── bootstrap.min.js
    │       └── jquery-1.11.3.min.js
    ├── components
    │   ├── home
    │   │   ├── home.cfg.js
    │   │   ├── home.ctrl.js
    │   │   ├── home-list.tpl.html
    │   │   ├── home.mdl.js
    │   │   └── home.tpl.html
    │   └── student
    │       ├── data
    │       │   ├── studentlist.json
    │       │   └── studentlist.json~
    │       ├── student.cfg.js
    │       ├── student.ctrl.js
    │       ├── student-edit.html
    │       ├── student-list.tpl.html
    │       ├── student.mdl.js
    │       ├── student.srv.js
    │       ├── student.tpl.html
    │       └── student.val.js
    ├── css
    │   └── style.css
    ├── index.html
    └── share
        └── ajax.srv.js

Folder assets sẽ chứa các thư viện mình cấn dùng, không phải do mình tự viết, bên cạnh các gói official của google mình dùng thêm angular-ui-router để dễ dàng config SPA.
Folder component chứa nhưng trang mình viết, ở đây các bạn sẽ thấy có 2 trang là student và home.
Folder share sẽ chứa nhưng cái common mà project cần dùng.
Về tên file mình đặt như vậy để nhìn vào có thể nhân biết nó là gì:

.cfg: chứa config chung của trang cần tạo
.mdl: module, tạo module cho trang
.srv: tạo service cho trang
.ctrl: tạo controller cho trang
.tpl: tạo template(html) cho trang.
.val: tạo DO (data object) cho trang

Đầu tiên mình nói đến file app.mdl.js


(function (jq) {
	'use strict';
	
	angular.
			module('example' , [
				'ngCookies', 
				'ngResource', 
				'ui.router',
				'share.networkServices',
				'example.home',
				'example.student']); // define a new application module 
} (jQuery));

Toàn bộ các trang web sẽ là 1 module lớn tên là example, các thành phần trong mảng là những module khác được inject vào. Các bàn cũng cần tìm hiểu về depedency injection khi làm việc với angular nữa nha, như bạn thấy có 2 module example.home và example.student đã được inject vào.

File index.html

<body ng-app="example"> <!-- apply our angular app to our site -->

		<!-- Menu -->
		<nav class="navbar navbar-inverse" role="navigation">
			<div class="navbar-header">
				<a class="navbar-brand" ui-sref="#">ExampleLogo</a>
			</div>
			<ul class="nav navbar-nav">
				<li><a ui-sref="home" ui-sref-active="active">Home</a></li>
				<li><a ui-sref="about" ui-sref-active="active">About</a></li>
				<li><a ui-sref="student" ui-sref-active="active">Student</a></li> 
			</ul>
		</nav>
		
		<!-- Content -->
		<div class="container">
			<!-- This is where we will inject our content -->
			<div ui-view> <!-- only one unnamed view within any template (or root html) -->
				
			</div>
		</div>
      
		
   </body>

Với việc sử dụng ng-app=“example” là web của bạn có thể dùng với angularJS, (tất nhiên nhớ load các file js lên hết nha)
Các bạn chú ý cái directive ui-view ở bên dưới. đây là directive của router-ui lib, khi bạn tạo SPA thì nhớ cái này, khi bất cứ trang con nào được mở thì nó sẽ được đẩy vào thẻ div có directive này.

file app.cfg.js


(function (jq) {
	'use strict';
	
	angular
			.module('example') // get the application module
			.config(appRouterConfig) // add configuration to the application level
			.run(['$rootScope', '$state', appInitialization]);
			
	function appRouterConfig($stateProvider, $urlRouterProvider) {
		$stateProvider
			.state('home', {
				url: '/home',
				templateUrl: 'components/home/home.tpl.html'
			})
			.state('student', {
				url: '/student',
				templateUrl: 'components/student/student.tpl.html',
				controller: 'example.student.StudentCtrl',
				controllerAs: 'studentCtrl',
				resolve: {
					initializeData: loadStudents
				}
			})
			.state('about', {
				url: '/about',
				template: '<h3>Single Page Application - version 1.0</h3>' // a simple template
			});
			
		// if none of the above states are matched, use this as the fallback
		//$urlRouterProvider.otherwise('/home'); // It means default to 'home' state
	}
	
	function appInitialization($rootScope, $state) {
		$state.go('student');
	}
	
	function loadStudents() {
		
	}
} (jQuery));

File này dùng để config ban đầu cho toàn bộ website của bạn, mình có vài cái chú ý như sau:

angular
			.module('example') 

Cái này có nghĩa là get module example bạn đã tạo trước đó sau đó config và run
còn trong file app.mdl.js là

angular
			.module('example',[]) 

là tạo mới (set) module, nhớ nhé.

function appRouterConfig dùng để định nghĩa state và url cho website SPA của bạn, như bạn thấy có 3 trang là Home, About, và Student sẽ có 3 state tương ứng.
Đối với mối trang con bạn sẽ có option khái báo có thể định nghĩa template, controler, alias cho controller, resolve thì có thể gọi là tiền xử lý trước khì vào trang đó.

resolve: {
					initializeData: loadStudents
				}

Ở đây là muốn load hết Students xong sẽ vào trang students.

.run(['$rootScope', '$state', appInitialization]);
function appInitialization($rootScope, $state) {
		$state.go('student');
	}

với config ở trên bạn có thể tạo setting ban đâu khi vào website, với đoạn code trên mình muốn khi người dùng access vào web mình thì sẽ chạy tới trang student luôn.

Bữa nay tới đây thôi he, có thời gian mình sẽ nói chi tiết bên trong trang student
Bạn có thể download từ github: https://github.com/nguyenhuuca/an-example
Nếu chạy trên chrome,ie bạn cần chạy trên localhost, Firefox thì không cần
Tài liệu tham khảo
https://github.com/johnpapa/angular-styleguide/blob/master/a1/
https://github.com/angular-ui/ui-router/wiki/Multiple-Named-views

6 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?