Angular.js is becoming more popular for single page application. Angular have no’s of feature which help you to build better and fast web application. Now in this post i am going to explain you how to build better and fast single page application i am also going to explain how routes work in angular.js.

 

Live Demo

Simple Single Page App

We’re going to make a simple site with PHP + MySQL backend. In this we are going to perform CURD operation using Angular + PHP. You can built great application using angular, but this tutorial will show many of the concepts needed for those larger projects.

Goals

  • Build simple app which perform CRUD operation on database without page refresh.
  • Build Pretty URL’s in Angular JS.

Step 1. Build database

As i told above we are going to use MySQL backend for this application so first we create database i am using XAMP for PHP and MySQL. My database table is very simple it has three column ID, Name and Email it just for learning purpose. So create table or else you run below code in your PHPMyAdmin after create database.

CREATE TABLE IF NOT EXISTS `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` text NOT NULL,
  `email` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;

After table was create we need to create a service which handle angular request also save data in database. I already make a post to through which you can learn web services please follow link.

Step 2. Creating PHP REST API

This step is backbone of our project because with help of service we can perform CRUD operation in our database. If have any knowledge about web service or REST API then it is very easy for your to understand what we are doing. I am using simple switch case.

<?php
	ob_start();
	$connection = new mysqli("localhost", "root", "", "sample");
	$msg = array();
	$r = $_GET['r'];
	$req = file_get_contents("php://input");
	$get = json_decode(stripslashes($req));
	switch($r){
		case "insert":
			$name = $get->name;
			$email = $get->email;
			$sql = "INSERT INTO `user` (`id`, `name`, `email`) VALUES (NULL, '$name', '$email');";
			
			if ($connection->query($sql)) {
				$msg['status'] = 1;
				$msg['msg'] = "Your record inserted successfully";
				} else {
				$msg['status'] = 0;
				$msg['msg'] = "Error inserting data";
			}
		break;
		case "list":
			$getData = "select * from user";
			$qur = $connection->query($getData);
			while($r = mysqli_fetch_assoc($qur)){
				$data[] = $r;
			}
			$msg['lists'] = $data;
		break;
		case "edit":
			$name = $get->name;
			$email = $get->email;
			$id = $get->id;
			 
			$query = "UPDATE `user` SET `name`='$name' ,`email`='$email' WHERE  `id`='$id'";
			if ($connection->query($query)) {
				$msg['status'] = 1;
				$msg['msg'] = "Record updated successfully";
			}else {
				$msg['status'] = 0;
				$msg['msg'] = "Error updating data";
			}
		break;
		case "delete":
			$id = $get->id;
			$query = "DELETE FROM `user` WHERE `id`='$id'";
			if ($connection->query($query)) {
				$msg['status'] = 1;
				$msg['msg'] = "Record Deleted successfully";
			} else {
				$msg['status'] = 0;
				$msg['msg'] = "Error";
			} 
		break;
		case "getById":
			$id = $get->id;
			$getData = "select * from user where id='$id'";
			$qur = $connection->query($getData);
			$msg['data'] = mysqli_fetch_assoc($qur);
		break;
	}
	
	// Json Response
	$json = $msg;
	@mysqli_close($connection);
	header('Access-Control-Allow-Origin: *');
	header('Access-Control-Allow-Headers: Content-Type');
	header('Content-Type: application/json');
	echo json_encode($json);
ob_flush();

$_GET[‘r’] – contain request and tell which case we have to run (eg. add, delete etc).

file_get_contents(“php://input”) – this method get all raw request send on server.

$get – this variable save decoded json data so we use it further.

And at the last we return json data back as a result with help of this

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Content-Type: application/json');
echo json_encode($json);
ob_flush();

Step 3. Single page application

Now let start creating your single page application here is mine application structure in root i create 2 folder one for service which contain above php code to handle request, and second folder is for template. Template folder contain view like add.html, edit.html, view.html. We load all these view according to request.

Single page application - angular routes

.htaccess

This file is use for URL rewriting this file help to handle url request.

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule ^(.*)$ index.php?air=$1 [L,QSA]

# secure htaccess file
<Files .htaccess>
 order allow,deny
 Deny from all
 Satisfy All
</Files>

app.js

This file is a core file which contain all required angular functionality. I assume that you already have some basic understanding of angular js.

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

In above code we find our app and load it or we initialize our angular application. Note you need to include angular library in your html file and also need to add angular route file. Routes only work if u add routes library in your project.

sampleApp.config(['$routeProvider', '$locationProvider',
	function ($routeProvider, $locationProvider) {
		$routeProvider.
		when('/edit/:orderId', {
			templateUrl: 'templates/edit.html',
			controller: 'editController'
		})
		.when('/add', {
			templateUrl: 'templates/add.html',
			controller: 'addController'
		})
		.when('/view', {
			templateUrl: 'templates/view.html',
			controller: 'viewController'
		})
		.otherwise({
			templateUrl: 'templates/view.html',
			controller: 'viewController'
		});
		
		// use the HTML5 History API
        $locationProvider.html5Mode(true);
}]);

In above code is easy to understand once you get know what is actual going do now here is simple eg. when user click on link browser url change on your click above config setting check that URL or request that they are math with it if the match they load specific template and its controller with it or if request is undefined it go to otherwise  and load default view for it.

 $locationProvider.html5Mode(true);

without above line you need to add # with every URL you want if you like to remove that # from browser add this line and remove this will change your url from  http://trinitytuts.com/#about to http://trinitytuts.com/about . With help of html5mode your URL work but if you are not using .htaccess file when you refresh your page it will show you 404 Error. So use this file to resolve this error. Now add following code to your app.js file below code contain controller which handle request.

sampleApp.controller('editController', function($scope, $routeParams, $location, $http) {
	$scope.id = $routeParams.orderId;
	$scope.getUserByID = function(){
		var request = $http({
			method: "post",
			url:  "http://localhost/angularRoutes/service/index.php?r=getById",
			data: {"id": $routeParams.orderId },
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		});
		request.success(function (res) {
			console.log(res);
			$scope.user = {
				name: res.data.name,
				email: res.data.email,
				id:  res.data.id
			};
		});
		request.error(function(serverResponse, status, headers, config) {
			/* Error loading data */
		});	
	};
	
	$scope.edit = function(){
		var data = $scope.user;
		var request = $http({
			method: "post",
			url:  "http://localhost/angularRoutes/service/index.php?r=edit",
			data: data,
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		});
		
		request.success(function (res) {
			console.log(res);
			if(res.status == 1){
				$scope.name = "";
				$scope.email = "";
				alert(res.msg);
			}else
			alert(res.msg);
		});
		request.error(function(serverResponse, status, headers, config) {
			/* Error loading data */
		});	
	};
	
});

sampleApp.controller('addController', function($scope, $http) {
	
	$scope.add = function(){
		var data = $scope.user;
		var request = $http({
			method: "post",
			url:  "http://localhost/angularRoutes/service/index.php?r=insert",
			data: data,
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		});
		
		request.success(function (res) {
			console.log(res);
			if(res.status == 1){
				$scope.name = "";
				$scope.email = "";
				alert(res.msg);
			}else
			alert(res.msg);
		});
		request.error(function(serverResponse, status, headers, config) {
			/* Error loading data */
		});	
	};
});

sampleApp.controller('viewController', function($scope, $http) {
	
	$scope.loadList = function(){
		var data = $scope.user;
		var request = $http({
			method: "get",
			url:  "http://localhost/angularRoutes/service/index.php?r=list",
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		});
		
		request.success(function (res) {
			console.log(res);
			$scope.lists = res.lists;
		});
		request.error(function(serverResponse, status, headers, config) {
			/* Error loading data */
		});	
	};
	
	$scope.remove = function(id){
		var data = $scope.user;
		var request = $http({
			method: "post",
			url:  "http://localhost/angularRoutes/service/index.php?r=delete",
			data: {"id": id },
			headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
		});
		
		request.success(function (res) {
			if(res.status == 1){
				$(".id-"+id).remove();
			}else
			alert(res.msg);
		});
		request.error(function(serverResponse, status, headers, config) {
			/* Error loading data */
		});	
	};
	
});

index.php

Create a default page for your app. In this page you can add all your required library and also you can load your template in this page.

<!DOCTYPE html>
<html lang="en">
	<head>	
		<meta charset="utf-8">
		<base href="http://localhost/angularRoutes/">
		<title>AngularJS Routing example</title>
		<!-- Latest compiled and minified CSS -->
		<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
		<!-- Optional theme -->
		<style>
			body {
			padding-top: 10px;
			background-color: #F5F5F5;
			}
		</style>
		<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
		<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
		<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular-route.min.js"></script>
		<script src="app.js"></script>
	</head>
	<body ng-app="sampleApp">
		<div class="container">
			<nav class="navbar navbar-default">
				<div class="container-fluid">
					<!-- Brand and toggle get grouped for better mobile display -->
					<div class="navbar-header">
						<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
							<span class="sr-only">Toggle navigation</span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
							<span class="icon-bar"></span>
						</button>
						<a class="navbar-brand" href="/">TrinityTuts</a>
					</div>
					
					<!-- Collect the nav links, forms, and other content for toggling -->
					<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
						
						
						<ul class="nav navbar-nav navbar-right">
							<li><a href="view">View</a></li>							
							<li><a href="add">Add</a></li>
						</ul>
					</div><!-- /.navbar-collapse -->
				</div><!-- /.container-fluid -->
			</nav>
		</div>
		<div class="container">
			<div ng-view></div>
		</div>
	</body>
</html>

In above page i am using bootstrap for designing and there default library. Please download complete code from above link. Hope you get some basic idea from this please comment i you want any help regarding this tutorial.