博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Create a restful application with AngularJS and CakePHP(III)
阅读量:6684 次
发布时间:2019-06-25

本文共 9782 字,大约阅读时间需要 32 分钟。

  hot3.png

#Create a restful application with AngularJS and CakePHP(III)

#Build the frontend pages with AngularJS

is one of the most popular JS frameworks.

If you have not used AngularJS framework before, you could read the official AngularJS tutorial as exercise.

##Prepare AngularJS resources

In this project, I do not want to build the AngularJS frontend application into a standalone project.

You can download a copy of AngularJS seed from AngularJS Github, extract files into your local disc, and copy the app folder into webroot folder of this project as the start point of the next steps.

The app folder should look like.

<pre> webroot /app /js app.js controllers.js directives.js filters.js services.js /img /css /lib /angular /bootstrap jquery.js /partials index.html </pre>

I place jquery, angular and bootstrap into the lib folder.

##index.html

index.html is the template of all pages.

<pre> &lt;!doctype html> &lt;html lang="en" ng-app="myApp"> &lt;head> &lt;meta charset="utf-8"> &lt;title>AngularJS CakePHP Sample APP&lt;/title> &lt;link href="lib/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> &lt;link rel="stylesheet" href="css/app.css"/> &lt;/head> &lt;body ng-controller="AppCtrl"> &lt;div class="navbar navbar-fixed"> &lt;div class="navbar-inner"> &lt;a class="brand" href="#"> &lt;msg key="title">&lt;/msg> &lt;/a> &lt;ul class="nav"> &lt;li ng-class="activeWhen(path() == '/posts')"> &lt;a href="#/posts">Posts&lt;/a> &lt;/li> &lt;li ng-class="activeWhen(path() == '/new-post')"> &lt;a href="#/new-post">New Post&lt;/a> &lt;/li> &lt;/ul> &lt;/div> &lt;/div> &lt;div class="container"> &lt;div ng-class="'alert alert-' + message().type" ng-show="message().show"> &lt;button type="button" class="close" ng-click="message().show = false">&times;&lt;/button> &lt;msg key-expr="message().text">&lt;/msg> &lt;/div> &lt;ng-view>&lt;/ng-view> &lt;div class="footer">Angular seed app: v&lt;span app-version>&lt;/span>&lt;/div> &lt;/div> &lt;!-- In production use: &lt;script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js">&lt;/script> --> &lt;script type="text/javascript" src="lib/jquery.js">&lt;/script> &lt;script type="text/javascript" src="lib/jquery.i18n.properties-min-1.0.9.js">&lt;/script> &lt;script type="text/javascript" src="lib/html5shiv.js">&lt;/script> &lt;script type="text/javascript" src="lib/holder.js">&lt;/script> &lt;script type="text/javascript" src="lib/bootstrap/js/bootstrap.min.js">&lt;/script> &lt;script type="text/javascript" src="lib/angular/angular.js">&lt;/script> &lt;script type="text/javascript" src="js/app.js">&lt;/script> &lt;script type="text/javascript" src="js/services.js">&lt;/script> &lt;script type="text/javascript" src="js/controllers.js">&lt;/script> &lt;script type="text/javascript" src="js/filters.js">&lt;/script> &lt;script type="text/javascript" src="js/directives.js">&lt;/script> &lt;/body> &lt;/html> </pre>

In the html elment, there is a ng-app attribute, which indicates this is an AngularJs application. In the js/app.js file, define a AngularJS module named myAPP, it includes submodules myApp.filters, myApp.directive, myApp.controllers, they are deifned in filters.js, directives.js, controllers.js files respectively.

<pre> as = angular.module('myApp', ['myApp.filters', 'myApp.services', 'myApp.directives', 'myApp.controllers']); </pre>

The index.html will work as a template, there is a ng-view element, which is a AngularJS specific directive, it will render the routing page content at runtime.

##Routing

In the js/app.js, define the path routing of Post list, add, edit page.

<pre> as.config(function($routeProvider, $httpProvider) { $routeProvider .when('/posts', {templateUrl: 'partials/posts.html', controller: 'PostListCtrl'}) .when('/new-post', {templateUrl: 'partials/new-post.html', controller: 'NewPostCtrl'}) .when('/edit-post/:id', {templateUrl: 'partials/edit-post.html', controller: 'EditPostCtrl'}) .otherwise({redirectTo: '/'}); }); </pre>

##Post List

Let's create the posts.html and PostListCtrl.

<pre> &lt;div ng-controller="PostListCtrl"> &lt;h1 class="page-header">Post List&lt;/h1> &lt;table class="table"> &lt;thead> &lt;tr> &lt;th width="25px">ID&lt;/th> &lt;th>TITLE&lt;/th> &lt;th>CONTENT&lt;/th> &lt;th>CREATED DATE&lt;/th> &lt;th width="50px">&lt;/th> &lt;/tr> &lt;/thead> &lt;tbody> &lt;tr ng-repeat="e in posts"> &lt;td>{

{e.Post.id}}&lt;/td> &lt;td>{
{e.Post.title}}&lt;/td> &lt;td>{
{e.Post.body}}&lt;/td> &lt;td>{
{e.Post.created|date:'short'}}&lt;/td> &lt;td>&lt;a ng-click="editPost($index)">&lt;i class="icon-pencil">&lt;/i> &lt;/a> &nbsp; &lt;a ng-click="delPost($index)">&lt;i class="icon-remove-circle">&lt;/i>&lt;/a>&lt;/td> &lt;/tr> &lt;/tbody> &lt;/table> &lt;/div> </pre>

In the posts.html, use a ng-repeat directive to interate the posts in a table.

Define a PostListCtrl in js/controllers.js.

<pre> as.controller('PostListCtrl', function($scope, $rootScope, $http, $location) { var load = function() { console.log('call load()...'); $http.get($rootScope.appUrl + '/posts.json') .success(function(data, status, headers, config) { $scope.posts = data.posts; angular.copy($scope.posts, $scope.copy); }); } load(); $scope.addPost = function() { console.log('call addPost'); $location.path("/new-post"); } $scope.editPost = function(index) { console.log('call editPost'); $location.path('/edit-post/' + $scope.posts[index].Post.id); } $scope.delPost = function(index) { console.log('call delPost'); var todel = $scope.posts[index]; $http .delete($rootScope.appUrl + '/posts/' + todel.Post.id + '.json') .success(function(data, status, headers, config) { load(); }).error(function(data, status, headers, config) { }); } }); </pre>

PostListCtrl will load the posts from REST API by default. In the scope of PostListCtrl, there are some other actions defined, addPost and editPost are use to navigate to a new add or edit page, and delPost will the selected Post immediately, and refresh the list after it is deleted successfully.

More info about scope and $http, please consult the online AngularJS document.

In browser, navigate to and click Post List link, you should see the screen like this.

AngularJS app posts

Add a new Post

According to the routing definition, we need to create a new-post.html page and a controller NewPostCtrl.

The new-post.html template.

<pre> &lt;div ng-controller="NewPostCtrl"> &lt;form class="form-horizontal"> &lt;h1 class="page-header">New Post&lt;/h1> &lt;fieldset> &lt;div class="control-group"> &lt;label class="control-label" for="title">Title&lt;/label> &lt;div class="controls"> &lt;input id="title" type="text" class="input-block-level" required="true" ng-model="post.title">&lt;/input> &lt;/div> &lt;/div> &lt;div class="control-group"> &lt;label class="control-label" for="body">Body&lt;/label> &lt;div class="controls"> &lt;textarea id="body" class="input-block-level" rows="10" ng-model="post.body" required="true">&lt;/textarea> &lt;/div> &lt;/div> &lt;/fieldset> &lt;div class="form-actions"> &lt;button class="btn btn-primary" ng-click="savePost()">Add Post&lt;/button> &lt;/div> &lt;/form> &lt;/div> </pre>

The NewPostCtrl controller.

<pre> as.controller('NewPostCtrl', function($scope, $rootScope, $http, $location) { $scope.post = {}; $scope.savePost = function() { console.log('call savePost'); var _data = {}; _data.Post = $scope.post; $http .post($rootScope.appUrl + '/posts.json', _data) .success(function(data, status, headers, config) { $location.path('/posts'); }).error(function(data, status, headers, config) { }); } }); </pre>

Add a button in the posts.html.

<pre> &lt;p> &lt;button type="button" class="btn btn-success" ng-click="addPost()"> &lt;b class="icon-plus-sign">&lt;/b>Add Post &lt;/button> &lt;/p> </pre>

Refresh your brower have a try now.

AngularJS app posts

##Edit Post

The template page and controller is similar with the add action, the difference is we must load the edit data from REST API before open the edit page.

The edit-post.html template.

<pre> &lt;div ng-controller="EditPostCtrl"> &lt;form class="form-horizontal"> &lt;h1 class="page-header">Edit Post({

{post.id}}, created at {
{post.created|date:'short'}})&lt;/h1> &lt;fieldset> &lt;div class="control-group"> &lt;label class="control-label" for="title">Title&lt;/label> &lt;div class="controls"> &lt;input id="title" type="text" class="input-block-level" required="true" ng-model="post.title">&lt;/input> &lt;/div> &lt;/div> &lt;div class="control-group"> &lt;label class="control-label" for="body">Body&lt;/label> &lt;div class="controls"> &lt;textarea id="body" class="input-block-level" rows="10" ng-model="post.body" required="true">&lt;/textarea> &lt;/div> &lt;/div> &lt;/fieldset> &lt;div class="form-actions"> &lt;button ng-click="updatePost()" class="btn btn-primary">Update Post&lt;/button> &lt;/div> &lt;/form> &lt;/div> </pre>

The EditPostCtrl controller.

<pre> as.controller('EditPostCtrl', function($scope, $rootScope, $http, $routeParams, $location) { var load = function() { console.log('call load()...'); $http.get($rootScope.appUrl + '/posts/' + $routeParams['id'] + '.json') .success(function(data, status, headers, config) { $scope.post = data.post.Post; angular.copy($scope.post, $scope.copy); }); } load(); $scope.post = {}; $scope.updatePost = function() { console.log('call updatePost'); var _data = {}; _data.Post = $scope.post; $http .put($rootScope.appUrl + '/posts/' + $scope.post.id + '.json', _data) .success(function(data, status, headers, config) { $location.path('/posts'); }).error(function(data, status, headers, config) { }); } }); </pre>

Try edit the new added post and save it.

AngularJS app edit post

##Summary

The basic CRUD implementation in AngularJS is simple and stupid, and all data communicated with the backend is via REST/JSON which we have done in the last post.

转载于:https://my.oschina.net/hantsy/blog/175305

你可能感兴趣的文章
今天访问量过3000了,自己留个脚印
查看>>
FFmpeg笔记 -- AVPacket、AVFrame
查看>>
工作区配置 4
查看>>
Android开发工程师,前行路上的14项技能
查看>>
w 查看系统负载 uptime vmsta 详解 top 详解 sar 命令 free 命令
查看>>
ps 查看进 netstat 查看端口
查看>>
网页图表Highcharts实践教程之认识Highcharts
查看>>
LPC2103学习之GPIO
查看>>
管理岗是什么鬼?
查看>>
创建一个当前时间凌晨
查看>>
Python 学习笔记 - 多进程和进程池
查看>>
日志切割实例
查看>>
CentOS安装中文汉字输入法ibus
查看>>
【环境配置】DOSBox运行TT打字软件
查看>>
Android中处理Touch Icon的方案
查看>>
RHEL7.1配置本地yum源
查看>>
Mybatis Generator最完整配置详解
查看>>
Hash学习
查看>>
PHP按符号截取字符串的指定部分
查看>>
在Blender导出格式为STL
查看>>