Angular 通常通过 AJAX 调用提供内容,因此您应该使用 CodeIgniter 作为 Web 服务 API 框架。
假设您要实现一个简单的列表:
首先,使用示例数据创建您的 Angular 项目(例如,通过硬编码值)。当您的产品列表正常工作时。
HTML
var app = angular.module('myApp', []);
app.controller('MainCtrl', function($scope) {
$scope.items = [
"One",
"Two",
"Three",
"Four"
];
});
angular.bootstrap(document, ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
<a href="">{{item}}</a>
</li>
</ul>
</div>
目前,元素是硬编码的。但是我们需要这些元素是动态的,CodeIgniter 提供数据。
为此,请在服务器的“www”文件夹中创建一个名为“api”的文件夹。然后上传所有 CodeIgniter 源文件。如果你操作正确,当你访问“http://yourdomain.com/api”时应该会看到“欢迎”控制器。
为此,我建议使用this CodeIgniter plugin,它可以让您轻松创建Webservice API Rest。主要目标是在 Angular 请求数据时提供一个 json 对象。然后 Angular 将完成剩下的工作。
一个简单的例子:
<?php
header("Content-type: application/json");
class List extends CI_Controller
{
function __construct()
{
// Here you can load stuff like models or libraries if you need
$this->load->model("list_model"); // For example
}
/**
* This method receives a parameter so it can
* filter what list wants the client to get
*/
public function list1($list_number)
{
$list = $this->list_model->getList($list_number);
// If list not exists
if ( empty($list) ) {
$this->output->set_status_header(404);
echo json_encode(
"success" => false,
);
return;
} else { // If has returned a list
// CodeIgniter returns an HTTP 200 OK by default
echo json_encode(
"success" => true,
"list" => $list,
);
return;
}
}
}
现在我们可以通过 AJAX 获取信息。上面的代码相同,但更改为获取远程数据:
var app = angular.module('myApp', []);
app.controller('MainCtrl', ['$scope', '$http', function($scope, $http) {
// Replace link bellow by the API url
// For this example it would be:
// http://yourdomain.com/api/list/list1/1
$http.get("https://codepen.io/anon/pen/VExQdK.js").
success(function(res) {
console.log(res);
if ( res.success == true ) {
$scope.items = res.items;
} else {
$scope.items = [];
}
});
}]);
angular.bootstrap(document, ['myApp']);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-controller="MainCtrl">
<ul>
<li ng-repeat="item in items">
<a href="">{{item.name}}</a>
</li>
</ul>
</div>
通过这种方式,您可以获得与 Angular 一起使用的功能齐全的 CodeIgniter API。我喜欢在不同的控制器中组织方法,所以代码的结构是“可读的”。
要修改或删除服务器上的数据,可以使用 $http.post 并发送参数告诉 CodeIgniter 需要执行哪种操作。请记住使用会话数据来保护修改/删除信息的 ajax 调用(例如,如果用户尝试更新其他用户的信息)。
这不是一个确定的方法,但它是我的。希望对你有所帮助。