Create a restful application with AngularJS and CakePHP(III)

Create a restful application with AngularJS and CakePHP(III)

Build the frontend pages with AngularJS

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.

webroot
    /app
        /js
            app.js
            controllers.js
            directives.js
            filters.js
            services.js

        /img
        /css
        /lib
            /angular
            /bootstrap
            jquery.js
        /partials
        index.html

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

index.html

index.html is the template of all pages.

 
        AngularJS CakePHP Sample APP
        

 

 
        

 

 
    
    
        

 

 
 
 
 
  
  
  
  

        

 

 
 
 
 
  
  
  
  
×

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.

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

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.

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: '/'});

});

Post List

Let's create the posts.html and PostListCtrl.

 
 
 
 
  
  
  
  

Post List

ID TITLE CONTENT CREATED DATE
{{e.Post.id}} {{e.Post.title}} {{e.Post.body}} {{e.Post.created|date:'short'}}  

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

Define a PostListCtrl in js/controllers.js.

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) {
            });
        }

});

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 http://localhost/app/index.html 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.

 
 
 
 
  
  
  
  

New Post

Title
Body
Add Post

The NewPostCtrl controller.

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) {
    });
}
});

Add a button in the posts.html.

Add Post

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.

 
 
 
 
  
  
  
  

Edit Post({{post.id}}, created at {{post.created|date:'short'}})

Title
Body
Update Post

The EditPostCtrl controller.

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) {
    });
}
});

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.

你可能感兴趣的:(apache,PHP,mysql,AngularJS,cakephp)