Posted by Arjun on Wednesday 3rd December 2014

AngularJS and Codeigniter : Retrieve data from the database

Here I would will like to show you how to use Angular JS in CodeIgniter and I will show you how to get data from the database in Codigniter using Angular JS.

view : angularjs_view.php

<!DOCTYPE html >
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Arjunphp.com</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0/angular.min.js"></script> 
<script type="text/javascript">
 function userController($scope,$http) {
	 $scope.users = [];
	 $http.get('<?php echo site_url('angularjs/get_list'); ?>').success(function($data){ $scope.users=$data; });
 }
</script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
</head>
<body ng-app>
<!-- ng-app : which tells the Angular framework to parse data from this div -->
<div class="container">
  <div class="col-lg-12 col-md-12">
    <table ng-controller="userController" class="table table-bordered table-condensed table-responsive">
      <thead>
        <tr>
          <td>S.no.</td>
          <td>Email</td>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="user in users">
          <td>{{user.id}}</td>
          <td>{{user.email}}</td>
        </tr>
      </tbody>
    </table>
  </div>
</div>

</body>
</html>

Controller: Angularjs.php

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

class Angularjs extends CI_Controller {

	public function index()
	{
		$this->load->helper(array('url'));
		$this->load->view('angularjs_view');
	}
	
	public function get_list() {
		$this->load->model(array('user_model'));
		$data = $this->user_model->getAll();
		$this->output->set_content_type('application/json')->set_output(json_encode($data));
	}
}

/* End of file Angularjs.php */
/* Location: ./application/controllers/Angularjs.php */

Model : User_model.php

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

class User_model extends CI_Model {
    
	protected $table_name;
	
	public function __construct() {
		parent::__construct();
		$this->load->database();
		$this->table_name = 'tbl_users';
	}
	
	public function getAll() {
		return $this->db->from($this->table_name)->get()->result_array();
	}

}

/* End of file user_model.php */
/* Location: ./application/controllers/user_model.php */

That's it.