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

Please read the following tutorials before reading this tutorial

Working with RESTful services in Codeigniter – GET example

Working with RESTful services in Codeigniter – POST example

Working with RESTful services in Codeigniter – PUT example

Working with RESTful services in Codeigniter – DELETE example

Codeigniter REST + ReactJS CRUD Example

You can also check AngularJS PHP REST CRUD Example

If you need AngularJS with Spring MVC, you can check here http://www.jeejava.com/spring-mvc-angularjs-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/contactService.js

'use strict';
 
angular.module('myCrudApp').factory('ContactService', ['$http', '$q', function($http, $q){
 
    var REST_SERVICE_URI = 'http://localhost/ci_3_1_0/index.php/';
 
    var factory = {
    	findAllContacts: findAllContacts,
        createContact: createContact,
        updateContact: updateContact,
        deleteContact: deleteContact
    };
 
    return factory;
 
    function findAllContacts() {
        var deferred = $q.defer();
        $http.get(REST_SERVICE_URI+'restgetcontroller/contacts')
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while fetching contacts');
                deferred.reject(errResponse);
            }
        );        
        return deferred.promise;
    }
 
    function createContact(contact) {
        var deferred = $q.defer();
        $http.post(REST_SERVICE_URI+'restpostcontroller/add_contact', contact)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while creating contact');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
 
    function updateContact(contact) {
        var deferred = $q.defer();
        $http.put(REST_SERVICE_URI+'restputcontroller/update_contact', contact)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while updating contact');
                deferred.reject(errResponse);
            }
        );
        return deferred.promise;
    }
 
    function deleteContact(id) {
        var deferred = $q.defer();
        $http.delete(REST_SERVICE_URI+'restdeletecontroller/delete_contact/'+id)
            .then(
            function (response) {
                deferred.resolve(response.data);
            },
            function(errResponse){
                console.error('Error while deleting contact');
                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/contactController.js

'use strict';
 
angular.module('myCrudApp').controller('ContactController', ['$scope', 'ContactService', function($scope, ContactService) {
    var self = this;
    self.contact = { contact_id: null, contact_name:'', contact_address:'', contact_phone:'' };
    self.contacts = [];
 
    self.submit = submit;
    self.edit = edit;
    self.remove = remove;
    self.reset = reset;
 
 
    findAllContacts();
 
    function findAllContacts(){        
    	ContactService.findAllContacts()
            .then(
            function(d) {
                self.contacts = d;
            },
            function(errResponse){
                console.error('Error while fetching contacts');
            }
        );
    }
 
    function createContact(contact){
    	ContactService.createContact(contact)
            .then(
            findAllContacts,
            function(errResponse){
                console.error('Error while creating contact');
            }
        );
    }
 
    function updateContact(contact){
    	ContactService.updateContact(contact)
            .then(
            findAllContacts,
            function(errResponse){
                console.error('Error while updating contact');
            }
        );
    }
 
    function deleteContact(id){
    	ContactService.deleteContact(id)
            .then(
            findAllContacts,
            function(errResponse){
                console.error('Error while deleting contact');
            }
        );
    }
 
    function submit() {
        if(self.contact.contact_id===null){
            console.log('Saving New Contact', self.contact);
            createContact(self.contact);
        }else{
            updateContact(self.contact);
            console.log('Contact updated with id ', self.contact.contact_id);
        }
        reset();
    }
 
    function edit(id){
        console.log('id to be edited', id);
        for(var i = 0; i < self.contacts.length; i++){
            if(self.contacts[i].contact_id === id) {
                self.contact = angular.copy(self.contacts[i]);
                break;
            }
        }
    }
 
    function remove(id){
        console.log('id to be deleted', id);
        if(self.contact.contact_id === id) {//clean form if the contact to be deleted is shown there.
            reset();
        }
        deleteContact(id);
    }
 
 
    function reset(){
        self.contact = { contact_id: null, contact_name:'', contact_address:'', contact_phone:'' };
        $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.

Now create ContactController class under <project root directory>/application/controllers directory

<?php

defined('BASEPATH') OR exit('No direct script access allowed');

require(APPPATH . '/libraries/REST_Controller.php');

/**
 * Description of ContactController
 *
 * @author https://roytuts.com
 */
class ContactController extends CI_Controller {

    function __construct() {
        parent::__construct();
    }

    function index() {
        $this->load->view('contact_crud');
    }

}

Update the <project root directory>/application/config/routes.php file to point the ContactController

$route['default_controller'] = 'contactcontroller';

Create below view file contact_crud.php under <project root directory>/application/views directory

<!DOCTYPE html>
<html>
    <head>
        <title>AngularJS Codeigniter 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="ContactController as ctrl">
          <div class="panel panel-default">
              <div class="panel-heading"><span class="lead">Create new contact</span></div>
              <div class="formcontainer">
                  <form ng-submit="ctrl.submit()" name="myForm" class="form-horizontal">
                      <input type="hidden" ng-model="ctrl.contact.contact_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.contact.contact_name" id="name" class="field form-control input-sm" placeholder="Enter contact 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-group col-md-12">
                              <label class="col-md-2 control-lable" for="address">Address</label>
                              <div class="col-md-7">
                                  <input type="text" ng-model="ctrl.contact.contact_address" id="address" class="field form-control input-sm" placeholder="Enter contact address" required ng-minlength="5"/>
                                  <div class="has-error" ng-show="myForm.$dirty">
                                      <span ng-show="myForm.address.$error.required">This is a required field</span>
                                      <span ng-show="myForm.address.$error.minlength">Minimum length required is 5</span>
                                      <span ng-show="myForm.address.$invalid">This field is invalid </span>
                                  </div>
                              </div>
                          </div>
                      </div>
                      
                      <div class="row">
                          <div class="form-group col-md-12">
                              <label class="col-md-2 control-lable" for="phone">Phone</label>
                              <div class="col-md-7">
                                  <input type="text" ng-model="ctrl.contact.contact_phone" id="address" class="field form-control input-sm" placeholder="Enter contact phone" required ng-minlength="10"/>
                                  <div class="has-error" ng-show="myForm.$dirty">
                                      <span ng-show="myForm.phone.$error.required">This is a required field</span>
                                      <span ng-show="myForm.phone.$error.minlength">Minimum length required is 10</span>
                                      <span ng-show="myForm.phone.$invalid">This field is invalid </span>
                                  </div>
                              </div>
                          </div>
                      </div>
 
                      <div class="row">
                          <div class="form-actions floatRight">
                              <input type="submit"  value="{{!ctrl.contact.contact_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 Contacts</span></div>
              <div class="tablecontainer">
                  <table class="table table-hover">
                      <thead>
                          <tr>
                              <th>ID</th>
                              <th>Name</th>
                              <th>Address</th>
                              <th>Phone</th>
                              <th width="20%"></th>
                          </tr>
                      </thead>
                      <tbody>
                          <tr ng-repeat="c in ctrl.contacts">
                              <td><span ng-bind="c.contact_id"></span></td>
                              <td><span ng-bind="c.contact_name"></span></td>
                              <td><span ng-bind="c.contact_address"></span></td>
                              <td><span ng-bind="c.contact_phone"></span></td>
                              <td>
                              	<button type="button" ng-click="ctrl.edit(c.contact_id)" class="btn btn-success custom-width">Edit</button>  <button type="button" ng-click="ctrl.remove(c.contact_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="<?php echo base_url();?>assets/js/app.js"></script>
        <script src="<?php echo base_url();?>assets/js/contactService.js"></script>
        <script src="<?php echo base_url();?>assets/js/contactController.js"></script>
    </body>
</html>

Now run the Codeigniter 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 *