You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用AngularJS与CodeIgniter构建CURD应用?求指导及实用链接

Hey there! I’ve built a handful of CRUD apps using AngularJS and CodeIgniter together, so I can walk you through the core workflow, key patterns, and practical code snippets to get you up and running. Let’s break this down step by step:

1. Project Structure & Initial Setup

First, organize your project so frontend and backend stay clean:

  • Keep your CodeIgniter backend in the root directory (stick to its standard setup: application/, system/, assets/).
  • Store AngularJS files inside assets/ for easy access:
    • assets/js/app.js (your main Angular module and controller)
    • assets/templates/ (for partial views if you need them)
    • assets/css/ (your stylesheets)

Critical CORS Config: Since Angular will make AJAX calls to your CodeIgniter API, add CORS headers to your controllers (or create a base controller to inherit from) to avoid cross-origin errors:

public function __construct() {
    parent::__construct();
    header("Access-Control-Allow-Origin: *"); // Restrict this to your frontend URL in production!
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, X-CSRF-Token");
}

Also, set your base_url in application/config/config.php to your server’s URL (e.g., http://localhost/your-project/).

2. Build the CodeIgniter Backend API

Create a dedicated API controller (e.g., Crud_api.php) to handle all CRUD operations, and a corresponding model (e.g., Item_model.php) for database interactions.

Example Controller (Crud_api.php)

class Crud_api extends CI_Controller {
    public function __construct() {
        parent::__construct();
        $this->load->model('Item_model');
        // Add the CORS headers here as mentioned above
    }

    // Fetch all items from the database
    public function get_items() {
        $items = $this->Item_model->get_all();
        echo json_encode($items);
    }

    // Add a new item
    public function add_item() {
        // Get JSON data sent from Angular
        $data = json_decode(file_get_contents('php://input'), true);
        
        // Validate input with CodeIgniter's form validation
        $this->form_validation->set_rules('name', 'Name', 'required');
        $this->form_validation->set_rules('description', 'Description', 'required');
        
        if ($this->form_validation->run()) {
            $item_id = $this->Item_model->insert($data);
            echo json_encode(['success' => true, 'id' => $item_id]);
        } else {
            echo json_encode(['success' => false, 'errors' => validation_errors()]);
        }
    }

    // Update an existing item (ID passed via URL)
    public function update_item($id) {
        $data = json_decode(file_get_contents('php://input'), true);
        $this->form_validation->set_rules('name', 'Name', 'required');
        
        if ($this->form_validation->run()) {
            $this->Item_model->update($id, $data);
            echo json_encode(['success' => true]);
        } else {
            echo json_encode(['success' => false, 'errors' => validation_errors()]);
        }
    }

    // Delete an item
    public function delete_item($id) {
        $this->Item_model->delete($id);
        echo json_encode(['success' => true]);
    }
}

Example Model (Item_model.php)

class Item_model extends CI_Model {
    private $table = 'items'; // Replace with your actual database table name

    public function get_all() {
        return $this->db->get($this->table)->result_array();
    }

    public function insert($data) {
        $this->db->insert($this->table, $data);
        return $this->db->insert_id();
    }

    public function update($id, $data) {
        $this->db->where('id', $id);
        return $this->db->update($this->table, $data);
    }

    public function delete($id) {
        $this->db->where('id', $id);
        return $this->db->delete($this->table);
    }
}

Don’t forget to set up your database connection in application/config/database.php!

3. Build the AngularJS Frontend

Create your main Angular app and controller to handle UI interactions and API calls.

Example app.js

var app = angular.module('crudApp', []);

app.controller('CrudController', function($scope, $http) {
    var baseUrl = 'http://localhost/your-project/crud_api/';

    // Load all items when the page loads
    $scope.loadItems = function() {
        $http.get(baseUrl + 'get_items')
            .then(function(response) {
                $scope.items = response.data;
            })
            .catch(function(error) {
                console.error('Failed to load items:', error);
                alert('Oops, couldn’t load items. Try again later.');
            });
    };

    // Add a new item to the database
    $scope.addItem = function() {
        $http.post(baseUrl + 'add_item', $scope.newItem)
            .then(function(response) {
                if (response.data.success) {
                    $scope.loadItems(); // Refresh the item list
                    $scope.newItem = {}; // Clear the form
                } else {
                    alert('Error adding item: ' + response.data.errors);
                }
            })
            .catch(function(error) {
                console.error('Failed to add item:', error);
            });
    };

    // Populate edit form with selected item
    $scope.editItem = function(item) {
        $scope.editingItem = angular.copy(item); // Copy to avoid modifying original while editing
    };

    // Save updated item to the database
    $scope.saveEdit = function() {
        $http.put(baseUrl + 'update_item/' + $scope.editingItem.id, $scope.editingItem)
            .then(function(response) {
                if (response.data.success) {
                    $scope.loadItems();
                    $scope.editingItem = null; // Hide the edit form
                } else {
                    alert('Error updating item: ' + response.data.errors);
                }
            })
            .catch(function(error) {
                console.error('Failed to update item:', error);
            });
    };

    // Delete an item from the database
    $scope.deleteItem = function(itemId) {
        if (confirm('Are you sure you want to delete this item?')) {
            $http.delete(baseUrl + 'delete_item/' + itemId)
                .then(function(response) {
                    if (response.data.success) {
                        $scope.loadItems();
                    }
                })
                .catch(function(error) {
                    console.error('Failed to delete item:', error);
                });
        }
    };

    // Initialize: load items when the controller starts
    $scope.loadItems();
});

Example View (index.php)

<!DOCTYPE html>
<html ng-app="crudApp">
<head>
    <title>Angular + CodeIgniter CRUD</title>
    <script src="assets/js/angular.min.js"></script> <!-- Use a local copy of AngularJS -->
    <script src="assets/js/app.js"></script>
    <!-- Add CSRF token for CodeIgniter security -->
    <meta name="csrf-token" content="<?php echo $this->security->get_csrf_hash(); ?>">
</head>
<body ng-controller="CrudController">
    <h2>Item Manager</h2>

    <!-- Add New Item Form -->
    <h3>Add New Item</h3>
    <form ng-submit="addItem()">
        <input type="text" ng-model="newItem.name" placeholder="Item Name" required>
        <input type="text" ng-model="newItem.description" placeholder="Item Description" required>
        <button type="submit">Add Item</button>
    </form>

    <!-- Edit Item Form (hidden until "Edit" is clicked) -->
    <div ng-if="editingItem" class="edit-form">
        <h3>Edit Item</h3>
        <form ng-submit="saveEdit()">
            <input type="text" ng-model="editingItem.name" required>
            <input type="text" ng-model="editingItem.description" required>
            <button type="submit">Save Changes</button>
            <button type="button" ng-click="editingItem = null">Cancel</button>
        </form>
    </div>

    <!-- List of Items -->
    <h3>Current Items</h3>
    <ul>
        <li ng-repeat="item in items">
            {{item.name}} - {{item.description}}
            <button ng-click="editItem(item)">Edit</button>
            <button ng-click="deleteItem(item.id)">Delete</button>
        </li>
    </ul>
</body>
</html>
4. Key Best Practices to Avoid Headaches
  • Double Validation: Always validate input on both the backend (CodeIgniter’s form validation) and frontend (Angular’s required directives or custom validation) to keep your data safe and user-friendly.
  • CSRF Protection: As shown in the view, add the CSRF token meta tag and configure Angular to send it with requests. Update your Angular config to include:
    app.config(function($httpProvider) {
        $httpProvider.defaults.headers.common['X-CSRF-Token'] = document.querySelector('meta[name="csrf-token"]').content;
    });
    
  • Error Handling: Never skip error callbacks in $http calls—they’ll help you debug API request issues quickly.
  • RESTful Routing: Clean up your API URLs with CodeIgniter routes in application/config/routes.php:
    $route['crud_api/get_items'] = 'crud_api/get_items';
    $route['crud_api/add_item'] = 'crud_api/add_item';
    $route['crud_api/update_item/(:num)'] = 'crud_api/update_item/$1';
    $route['crud_api/delete_item/(:num)'] = 'crud_api/delete_item/$1';
    

If you run into specific issues—like database errors, AJAX call failures, or UI glitches—feel free to share more details, and I can help troubleshoot further!

内容的提问来源于stack exchange,提问作者Tanwir Alam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:23:53