In this tutorial we will see the integration of AngularJS with PHP REST. We are going to create CRUD application using PHP REST API on server side and AngularJS is encapsulated within html file on client side. Thus the client will communicate with server asynchronously using AngularJS $http service.

Please read REST API CRUD Example in PHP, MySQL for server side before reading this tutorial.

If you need AngularJS with Spring MVC, you can check here http://www.jeejava.com/spring-mvc-angularjs-crud-example/

Codeigniter REST + ReactJS CRUD Example

AngularJS module

The angular.module is a global place for creating, registering and retrieving AngularJS modules. A module is a collection of services, directives, controllers, filters, and configuration information. angular.module is used to configure the $injector.

A module can be used by AngularJS to bootstrap an application. AngularJS loads a module by passing the module name to ng-app directive and it is the main entry point for the application.

Create a new module using the following code snippets

<project root directory>/assets/js/app.js

'use strict';
var app = angular.module('myCrudApp', []);

'use strict' does the following

  • It catches some common coding bloopers, throwing exceptions.
  • It prevents, or throws errors, when relatively “unsafe” actions are taken (such as gaining access to the global object).
  • It disables features that are confusing or poorly thought out.

AngularJS Service to communicate with Server

<project root directory>/assets/js/departmentService.js

'use strict';
 
angular.module('myCrudApp').factory('DepartmentService', ['$http', '$q', function($http, $q){
 
    var REST_SERVICE_URI = 'http://localhost/php-angularjs/';
 
    var factory = {
    	findAllDepartments: findAllDepartments,
        createDepartment: createDepartment,
        updateDepartment: updateDepartment,
        deleteDepartment: deleteDepartment
    };
 
    return factory;
 
    function findAllDepartments() {
        var deferred = $q.defer();
        $http.get(REST_SERVICE_URI+'department/read.php')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while fetching departments');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
    function createDepartment(department) {
        var deferred = $q.defer();
        $http.post(REST_SERVICE_URI+'department/create.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while creating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
 
    function updateDepartment(department) {
        var deferred = $q.defer();
        $http.put(REST_SERVICE_URI+'department/update.php', department)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while updating department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
    function deleteDepartment(id) {
        var deferred = $q.defer();
        $http.delete(REST_SERVICE_URI+'department/delete.php?id='+id)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while deleting department');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
}]);

Note: do not forget to change the value of REST_SERVICE_URI

In AngularJS based applications, the preferred way to communicate with server is using AngularJS built-in $http Service. AngularJS $http service allows us to communicate with server endpoints using XHR [browser’s XMLHttpRequest Object] API. The $http API is based on the deferred/promise APIs exposed by the $q service(https://docs.angularjs.org/api/ng/service/$q) which is an implementation of Promise interface, which is a standardized way of dealing with asynchronous calls in JavaScript.

AngularJS Controller to handle user’s request/response

<project root directory>/assets/js/departmentController.js

'use strict';
 
angular.module('myCrudApp').controller('DepartmentController', ['$scope', 'DepartmentService', function($scope, DepartmentService) {
    var self = this;
    self.department = { id: null, name:'' };
    self.departments = [];
 
    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;
 
 
    findAllDepartments();
 
    function findAllDepartments(){
    	DepartmentService.findAllDepartments()
            .then(
            function(d) {
                self.departments = d;
            },
            function(errResponse){
                console.error('Error while fetching departments');
            }
        );
    }
 
    function createDepartment(department){
    	DepartmentService.createDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while creating department');
            }
        );
    }
 
    function updateDepartment(department){
    	DepartmentService.updateDepartment(department)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while updating department');
            }
        );
    }
 
    function deleteDepartment(id){
    	DepartmentService.deleteDepartment(id)
            .then(
            findAllDepartments,
            function(errResponse){
                console.error('Error while deleting department');
            }
        );
    }
 
    function submit() {
        if(self.department.id===null){
            console.log('Saving New Department', self.department);
            createDepartment(self.department);
        }else{
            updateDepartment(self.department);
            console.log('Department updated with id ', self.department.id);
        }
        reset();
    }
 
    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.departments.length; i++){
            if(self.departments[i].id === id) {
                self.department = angular.copy(self.departments[i]);
                break;
            }
        }
    }
 
    function remove(id){
        console.log('id to be deleted', id);
        if(self.department.id === id) {//clean form if the department to be deleted is shown there.
            reset();
        }
        deleteDepartment(id);
    }
 
 
    function reset(){
        self.department={id:null, name:''};
        $scope.myForm.$setPristine(); //reset Form
    }
 
}]);

Controllers are considered as the driver for Model and View changes. They are the gateway between the model (the data in our application), and the view (whatever a user sees on screen and interacts with). The core responsibilities includes, providing data to UI, managing presentation logic, such as which element to show/hide, what style to apply on them, etc, handling user input, such as what happens when a user clicks something or how a text input should be validated, processing data from user input to be sent to server etc.

View for PHP application

<project root directory>/index.html

<!DOCTYPE html>
<html>
    <head>
        <title>AngularJS PHP Example</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">

        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
        <link href="assets/css/app.css" rel="stylesheet"/>
    </head>
    <body ng-app="myCrudApp" class="ng-cloak">
        <div class="generic-container" ng-controller="DepartmentController as ctrl">
          <div class="panel panel-default">
              <div class="panel-heading"><span class="lead">Create new department</span></div>
              <div class="formcontainer">
                  <form ng-submit="ctrl.submit()" name="myForm" class="form-horizontal">
                      <input type="hidden" ng-model="ctrl.department.id" />
                      <div class="row">
                          <div class="form-group col-md-12">
                              <label class="col-md-2 control-lable" for="name">Name</label>
                              <div class="col-md-7">
                                  <input type="text" ng-model="ctrl.department.name" id="name" class="field form-control input-sm" placeholder="Enter department name" required ng-minlength="3"/>
                                  <div class="has-error" ng-show="myForm.$dirty">
                                      <span ng-show="myForm.name.$error.required">This is a required field</span>
                                      <span ng-show="myForm.name.$error.minlength">Minimum length required is 3</span>
                                      <span ng-show="myForm.name.$invalid">This field is invalid </span>
                                  </div>
                              </div>
                          </div>
                      </div>
 
                      <div class="row">
                          <div class="form-actions floatRight">
                              <input type="submit"  value="{{!ctrl.department.id ? 'Add' : 'Update'}}" class="btn btn-primary btn-sm" ng-disabled="myForm.$invalid">
                              <button type="button" ng-click="ctrl.reset()" class="btn btn-warning btn-sm" ng-disabled="myForm.$pristine">Reset Form</button>
                          </div>
                      </div>
                  </form>
              </div>
          </div>
          <div class="panel panel-default">
              <div class="panel-heading"><span class="lead">List of Departments</span></div>
              <div class="tablecontainer">
                  <table class="table table-hover">
                      <thead>
                          <tr>
                              <th>ID</th>
                              <th>Name</th>
                              <th width="30%"></th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr ng-repeat="d in ctrl.departments">
                              <td><span ng-bind="d.id"></span></td>
                              <td><span ng-bind="d.name"></span></td>
                              <td>
                              	<button type="button" ng-click="ctrl.edit(d.id)" class="btn btn-success custom-width">Edit</button>  <button type="button" ng-click="ctrl.remove(d.id)" class="btn btn-danger custom-width">Remove</button>
                              </td>
                          </tr>
                      </tbody>
                  </table>
              </div>
          </div>
      </div>

        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.js"></script>
        <script src="assets/js/app.js"></script>
        <script src="assets/js/departmentService.js"></script>
        <script src="assets/js/departmentController.js"></script>
    </body>
</html>

Now run the php application and play with it.

If you need AngularJS with Spring MVC, you can check here http://www.jeejava.com/spring-mvc-angularjs-crud-example/

Codeigniter REST + ReactJS CRUD Example

Thanks for reading.

Tags:

I am a professional Web developer, Enterprise Application developer, Software Engineer and Blogger. Connect me on JEE Tutorials | TwitterFacebook Google PlusLinkedin | Reddit | Email Me

Leave a Reply

Your email address will not be published. Required fields are marked *