1. 程式人生 > >前端分層開發(MVC分層)、控制器繼承(程式碼重用)

前端分層開發(MVC分層)、控制器繼承(程式碼重用)

1.1 需求分析

  • 完成了品牌的增刪查改功能,但是JS程式碼和HTML程式碼都放在一起,並不利於我們後期維護。我們可以在前端程式碼中也運用MVC的模式,將程式碼進行分離,提高程式的可維護性。

1.2MVC分層

 1.2.1前端基礎模組層

在sunny-manager-web/src/main/webapp/js目錄下建立base.js:

/** 定義基礎模組(不帶分頁模組) */
var app = angular.module('sunny',[]);

再建立base-pagination.js:(帶分頁)

/**

定義基礎模組(帶分頁模組) */
var app = angular.module('sunny',['pagination']);

說明:一個用於需要分頁功能的頁面,一個用於需要分頁功能的頁面。基礎模組,必須有模組才能新增服務和控制器。

1.2.2 前端服務層

服務層:與伺服器互動,傳送非同步請求。(模組新增服務,控制器依賴服務)

A.在sunny-manager-web/src/main/webapp/js下面建立service資料夾。

B.在sunny-manager-web/src/main/webapp/js/service/資料夾下面建立baseService.js檔案。

C.在sunny-manager-web/src/main/webapp/js/service/下面建立品牌服務層brandService.js檔案。

/** 品牌服務層 */
app
.service("brandService", function($http){
});
 

 1.2.3前端控制層

控制器層:呼叫服務層獲取響應資料,並用$scope繫結。(模組新增控制器,控制器依賴服務)

 在sunny-manager-web的src/main/webapp/js資料夾下建立controller資料夾,再建立brandController.js:

/** 
定義品牌控制器層 */ app.controller('brandController', function($scope, baseService){     /** 定義分頁配置資訊物件 */     $scope.paginationConf = {         currentPage : 1, // 當前頁碼         totalItems : 0, // 總記錄數         itemsPerPage : 10, // 每頁顯示的記錄數         perPageOptions : [10,15,20], // 頁碼下拉列表         onChange : function() { // 改變事件             $scope.reload();         }     };     /** 當下拉列表頁碼發生改變,重新載入資料 */     $scope.reload = function(){         $scope.search($scope.paginationConf.currentPage,             $scope.paginationConf.itemsPerPage);     };     /** 定義搜尋物件 */     $scope.searchEntity = {};     /** 分頁查詢品牌 */     $scope.search = function(page, rows){          baseService.findByPage("/brand/findByPage", page,
rows, $scope.searchEntity)

            .then(function(response){

                $scope.dataList = response.data.rows;

                /** 更新總記錄數 */

                $scope.paginationConf.totalItems = response.data.total;

            });

    };

    /** 新增或修改品牌 */

    $scope.saveOrUpdate = function(){

        var url = "save";

        if ($scope.entity.id){

            url = "update";

        }

        /** 傳送post請求新增品牌 */

        baseService.sendPost("/brand/" + url, $scope.entity)

            .then(function(response){

                if (response.data){

                    /** 重新載入品牌資料 */

                    $scope.reload();

                }else{

                    alert("操作失敗!");

                }

            });

    };

    /** 顯示修改 */

    $scope.show = function(entity){

        // entityjson物件轉化成一個新的json物件

        $scope.entity = JSON.parse(JSON.stringify(entity));

};

   
/** 定義ids陣列封裝刪除的id */
   
$scope.ids = [];
   
/** 定義checkbox點選事件函式 */
   
$scope.updateSelection = function($event, id){
       
/** 判斷checkbox是否選中 */
       
if ($event.target.checked){
            $scope.
ids.push(id);
        }
else{
           
/** 從陣列中移除 */
           
var idx = $scope.ids.indexOf(id);
            $scope.
ids.splice(idx, 1);
        }
    };
   
/** 批量刪除 */
   
$scope.delete = function(){
       
if ($scope.ids.length > 0){
           
baseService.deleteById("/brand/delete", $scope.ids)
                .then(function(response){
                   
if (response.data){
                        $scope.
reload();
                    }
else{
                        alert(
"刪除失敗!");
                    }
                });
        }
    };
});
 

 1.2.4 修改頁面(引入剛剛定義的檔案)

去掉sunny-manager-web/src/main/webapp/admin/brand.html原來的js程式碼,引入剛才我們建立的js: 

<script src="/js/base-pagination.js"></script>
<
script src="/js/service/baseService.js"></script>
<
script src="/js/controller/brandController.js"></script>


2.1 控制器繼承(程式碼重用)

2.1.1 需求分析

  • 有些功能是每個頁面都有可能用到,比如分頁,複選等等,如果我們再開發另外一個功能,還需要重複編寫。怎麼讓這些通用的功能只寫一次呢?我們通過繼承的方式來實現

 2.1.2 前端程式碼

2.1.2.1 建立父控制器

在sunny-manager-web/src/main/webapp/js/controller/目錄下建立baseController.js

/** 定義基礎控制器層 */
app
.controller('baseController',function($scope){
   
/** 定義分頁配置資訊物件 */
   
$scope.paginationConf = {
       
currentPage : 1, // 當前頁碼
       
totalItems : 0, // 總記錄數
       
itemsPerPage : 10, // 每頁顯示的記錄數
       
perPageOptions : [10,15,20], // 頁碼下拉列表
       
onChange : function() { // 改變事件
           
$scope.reload();
        }
    };
   
/** 當下拉列表頁碼發生改變,重新載入資料 */
   
$scope.reload = function(){
        $scope.
search($scope.paginationConf.currentPage,
            $scope.
paginationConf.itemsPerPage);
    };
   
/** 定義ids陣列封裝刪除的id */
   
$scope.ids = [];
   
/** 定義checkbox點選事件函式 */
   
$scope.updateSelection = function($event, id){
       
/** 判斷checkbox是否選中 */
       
if ($event.target.checked){
            $scope.
ids.push(id);
        }
else{
           
/** 從陣列中移除 */
           
var idx = $scope.ids.indexOf(id);
            $scope.
ids.splice(idx, 1);
        }
    };
});

 2.1.2.2 修改品牌控制器

sunny-manager-web/src/main/webapp/js/controller/brandController.js: 

/** 品牌控制器層 */

app.controller("brandController", function($scope, $controller, baseService){

    /** 指定繼承baseController */

    $controller('baseController',{$scope:$scope});

    /** 讀取品牌資料繫結到表格中 */

    $scope.findAll = function(){

        /** 呼叫服務層查詢所有品牌資料 */

        baseService.sendGet("/brand/findAll").then(function(response){

            $scope.dataList = response.data;

        });

    };

    /** 定義搜尋物件 */

    $scope.searchEntity = {};

    /** 分頁查詢品牌資訊 */

    $scope.search = function(page, rows){

        /** 呼叫服務層分頁查詢品牌資料 */

        baseService.findByPage("/brand/findByPage",page,
rows,$scope.searchEntity)

            .then(function(response){

                $scope.dataList = response.data.rows;

                /** 更新總記錄數 */

                $scope.paginationConf.totalItems = response.data.total;

            });

    };

    /** 新增與修改品牌 */

    $scope.saveOrUpdate = function(){

        /** 定義請求URL */

        var url = "save"; // 新增品牌

        if ($scope.entity.id){

            url = "update"; // 修改品牌

        }

        /** 呼叫服務層 */

        baseService.sendPost("/brand/" + url, $scope.entity)

            .then(function(response){

                if (response.data){

                    /** 重新載入品牌資料 */

                    $scope.reload();

                }else{

                    alert("操作失敗");

                }

            });

    };

    /** 顯示修改,為修改表單綁定當行資料 */

    $scope.show = function(entity){

       // entityjson物件轉化成一個新的json物件

        $scope.entity = JSON.parse(JSON.stringify(entity));

};
   
/** 批量刪除品牌 */
   
$scope.delete = function(){
       
if ($scope.ids.length > 0){
           
/** 呼叫服務層 */
          
 
baseService.deleteById("/brand/delete", $scope.ids).then(
                function(response){
                   
if(response.data){
                       
/** 重新載入品牌資料 */
                       
$scope.reload();
                    }
                }
            );
        }
else{
            alert(
"請選擇要刪除的品牌!");
        }
    };
});

說明:$controller也是AngularJS提供的一個服務,可以實現偽繼承,實際上就是與baseController共享$scope 

  2.1.2.3 修改頁面

修改sunny-manager-web/src/main/webapp/admin/brand.html頁面:引入baseController.js

<script src="/js/base-pagination.js"></script>
<
script src="/js/service/baseService.js"></script>
<script src="/js/controller/baseController.js"></script>
<script src="/js/controller/brandController.js"></script>