Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Lets start by creating a new database name `angular_crud` then run the following SQL:

1. CREATE TABLE IF NOT EXISTS `users` (


2. `id` int(11) NOT NULL AUTO_INCREMENT,
3. `username` varchar(255) NOT NULL,
4. `first_name` varchar(100) NOT NULL,
5. `last_name` varchar(100) NOT NULL,
6. `address` varchar(255) DEFAULT NULL,
7. PRIMARY KEY (`id`)
8. ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
9.
10. --
11. -- Sample Data
12. --
13.
14. INSERT INTO `users` (`id`, `username`, `first_name`, `last_name`, `address`) VALUES
15. (1, 'lucentx', 'Aron', 'Barbosa', 'Manila, Philippines'),
16. (2, 'ozzy', 'Ozzy', 'Osbourne', 'England'),
17. (3, 'tony', 'Tony', 'Iommi', 'England');
Ive added sample data in the sql file so it would be easier. Now lets try to show those data
on a webpage.
(This requires a web server installed. Checkout XAMPP, WAMP, etc.)
Download the files for the part 1 of the tutorial here then Ill walk you through the code.
First lets take a look at the index.html :
12345678910111213141516
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>AngularJs</title>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootst
rap-combined.min.css" rel="stylesheet">
<body ng-app="CrudApp">

<div class="container">
<div ng-view></div>
</div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/a
ngularjs/1.0.7/angular.min.js"></script>
<script type="text/javascript" src ="assets/js/app.js"></script>
</body>
</html>
view rawindex.html hosted with by GitHub
Take note of the two directives in the index.html file. On line 7 we have the ng-app
directive, it is used to auto-bootstrap our angular application module which is the CrudApp
in assets/js/app.js . Read more about ng-app here. The second directive is the ng-view
directive. It will act as the view for our application.
Now lets check out our angular app.
1. angular.module('CrudApp', []).
2. config(['$routeProvider', function($routeProvider) {
3. $routeProvider.
4. when('/', {templateUrl: 'assets/tpl/lists.html', controller: ListCtrl}).
5. when('/add-user', {templateUrl: 'assets/tpl/add-new.html', controller: AddCtrl}).
6. otherwise({redirectTo: '/'});
7. }]);
8.
9. function ListCtrl($scope, $http) {
10. $http.get('api/users').success(function(data) {
11. $scope.users = data;
12. });
13. }
14.
15. function AddCtrl($scope, $http, $location) {
16. $scope.master = {};
17. $scope.activePath = null;
18.
19. $scope.add_new = function(user, AddNewForm) {
20. console.log(user);
21.
22. $http.post('api/add_user', user).success(function(){
23. $scope.reset();
24. $scope.activePath = $location.path('/');
25. });
26.
27. $scope.reset = function() {
28. $scope.user = angular.copy($scope.master);
29. };
30.
31. $scope.reset();
32.
33. };
34. }
Line 1 to 7 is our CrudApp angular module. Here we have the application routes which are
declared by $routeProvider. This service makes it easy to wire together controllers, view
templates, and the current URL location in the browser. As you can see in line 4, it means
that will use the assets/tpl/lists.html template and the ListCtrl controller. Our ListCtrl
controller utilizes the scope and $http service.
scope is an object that refers to the application
model. It is an execution context for expressions. Scopes are arranged in hierarchical
structure which mimic the DOM structure of the application. Scopes can
watch expressions and propagate events.
The $http service is a core Angular service that facilitates communication with the
remote
HTTP servers via the browsers XMLHttpRequest object or via JSONP.
So for the the ListCtrl controller, were trying to list all the users from the database using
our angular app.
Using the $http service, we can send a get request for all the users in our database. Thats
where slim php comes in. If you try to check api/index.php below:
1. require 'Slim/Slim.php';
2.
3. $app = new Slim();
4. $app->get('/users', 'getUsers');
5. $app->post('/add_user', 'addUser');
6.
7.
8. $app->run();
9.
10. function getUsers() {
11. $sql = "select * FROM users ORDER BY id";
12. try {
13. $db = getConnection();
14. $stmt = $db->query($sql);
15. $wines = $stmt->fetchAll(PDO::FETCH_OBJ);
16. $db = null;
17. echo json_encode($wines);
18. } catch(PDOException $e) {
19. echo '{"error":{"text":'. $e->getMessage() .'}}';
20. }
21. }
22.
23. function addUser() {
24. $request = Slim::getInstance()->request();
25. $user = json_decode($request->getBody());
26. $sql = "INSERT INTO users (username, first_name, last_name, address) VALUES (:username, :first_name, :last_
name, :address)";
27. try {
28. $db = getConnection();
29. $stmt = $db->prepare($sql);
30. $stmt->bindParam("username", $user->username);
31. $stmt->bindParam("first_name", $user->first_name);
32. $stmt->bindParam("last_name", $user->last_name);
33. $stmt->bindParam("address", $user->address);
34. $stmt->execute();
35. $user->id = $db->lastInsertId();
36. $db = null;
37. echo json_encode($user);
38. } catch(PDOException $e) {
39. echo '{"error":{"text":'. $e->getMessage() .'}}';
40. }
41. }
42.
43. function getConnection() {
44. $dbhost="127.0.0.1";
45. $dbuser="root";
46. $dbpass="";
47. $dbname="angular_tutorial";
48. $dbh = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
49. $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
50. return $dbh;
51. }
we can see that when we request for api/users it will return the data in json format:
1. [{
2. "id":"1",
3. "username":"lucentx",
4. "first_name":"Aron",
5. "last_name":"Barbosa",
6. "address":"Manila, Philippines"
7. },
8. {
9. "id":"2",
10. "username":"ozzy",
11. "first_name":"Ozzy",
12. "last_name":"Osbourne",
13. "address":"England"
14. },
15. {
16. "id":"3",
17. "username":"tony",
18. "first_name":"Tony",
19. "last_name":"Iommi",
20. "address":"England"
21. }]
The returned data is assigned to $scope.users in our ListCtrl controller:
1. function ListCtrl($scope, $http) {
2. $http.get('api/users').success(function(data) {
3. $scope.users = data;
4. });
5. }
Then we use ngRepeat to iterate the returned data into our template
( assets/tpl/lists.html ):
1234567891011121314151617181920
<h2>Users</h2>
<table class="table table-condensed">
<thead>
<tr>
<th>Username</th>
<th>First Name</th>
<th>Last Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="user in users">
<td>{{user.username}}</td>
<td>{{user.first_name}}</td>
<td>{{user.last_name}}</td>
<td>{{user.address}}</td>
</tr>
</tbody>
</table>
<a class="btn btn-primary" href="#/add-user">Add New User
</a>

You might also like