品優購電商系統開發
第2章
品牌管理
傳智播客.黑馬程序員
1.前端框架AngularJS入門
1.1 AngularJS簡介
AngularJS 誕生於2009年,由Misko Hevery 等人創建,后為Google所收購。是一款優秀的前端JS框架,已經被用於Google的多款產品當中。AngularJS有着諸多特性,最為核心的是:MVC、模塊化、自動化雙向數據綁定、依賴注入等等。
1.2 AngularJS四大特征
1.2.1 MVC模式
Angular遵循軟件工程的MVC模式,並鼓勵展現,數據,和邏輯組件之間的松耦合.通過依賴注入(dependency injection),Angular為客戶端的Web應用帶來了傳統服務端的服務,例如獨立於視圖的控制。 因此,后端減少了許多負擔,產生了更輕的Web應用。
Model:數據,其實就是angular變量($scope.XX);
View: 數據的呈現,Html+Directive(指令); {{方法或者變量}}
Controller:操作數據,就是function,數據的增刪改查;
1.2.2雙向綁定
AngularJS是建立在這樣的信念上的:即聲明式編程應該用於構建用戶界面以及編寫軟件構建,而指令式編程非常適合來表示業務邏輯。框架采用並擴展了傳統HTML,通過雙向的數據綁定來適應動態內容,雙向的數據綁定允許模型和視圖之間的自動同步。因此,AngularJS使得對DOM的操作不再重要並提升了可測試性。
1.2.3依賴注入
依賴注入(Dependency Injection,簡稱DI)是一種設計模式, 指某個對象依賴的其他對象無需手工創建,只需要“吼一嗓子”,則此對象在創建時,其依賴的對象由框架來自動創建並注入進來,其實就是最少知識法則;模塊中所有的service和provider兩類對象,都可以根據形參名稱實現DI.
1.2.4模塊化設計
高內聚低耦合法則
1)官方提供的模塊 ng、ngRoute、ngAnimate
2)用戶自定義的模塊 angular.module('模塊名',[ ]) []:可以添加其他模塊
1.3入門小Demo
1.3.1 表達式
<html> <head> <title>入門小Demo-1</title> <script src="angular.min.js"></script> </head> <body ng-app> {{100+100}} </body> </html> |
執行結果如下:
表達式的寫法是{{表達式 }} 表達式可以是變量或是運算式
ng-app 指令 作用是告訴子元素一下的指令是歸angularJs的,angularJs會識別的
ng-app 指令定義了 AngularJS 應用程序的 根元素。
ng-app 指令在網頁加載完畢時會自動引導(自動初始化)應用程序。
1.3.2 雙向綁定
<html> <head> <title>入門小Demo-1 雙向綁定</title> <script src="angular.min.js"></script> </head> <body ng-app> 請輸入你的姓名:<input ng-model="myname"> <br> {{myname}},你好 </body> </html> |
運行效果如下:
ng-model 指令用於綁定變量,這樣用戶在文本框輸入的內容會綁定到變量上,而表達式可以實時地輸出變量。
1.3.3 初始化指令
我們如果希望有些變量具有初始值,可以使用ng-init指令來對變量初始化
<html> <head> <title>入門小Demo-3 初始化</title> <script src="angular.min.js"></script> </head> <body ng-app ng-init="myname='陳大海'"> 請輸入你的姓名:<input ng-model="myname"> <br> {{myname}},你好 </body> </html> |
1.3.4 控制器
<html> <head> <title>入門小Demo-3 初始化</title> <script src="angular.min.js"></script> <script> var app=angular.module('myApp',[]); //定義了一個叫myApp的模塊 //定義控制器 app.controller('myController',function($scope){ $scope.add=function(){ return parseInt($scope.x)+parseInt($scope.y); } }); </script> </head> <body ng-app="myApp" ng-controller="myController"> x:<input ng-model="x" > y:<input ng-model="y" > 運算結果:{{add()}} </body> </html> |
運行結果如下:
ng-controller用於指定所使用的控制器。
理解 $scope:
$scope 的使用貫穿整個 AngularJS App 應用,它與數據模型相關聯,同時也是表達式執行的上下文.有了$scope 就在視圖和控制器之間建立了一個通道,基於作用域視圖在修改數據時會立刻更新 $scope,同樣的$scope 發生改變時也會立刻重新渲染視圖.
1.3.5 事件指令
<html> <head> <title>入門小Demo-5 事件指令</title> <script src="angular.min.js"></script> <script> var app=angular.module('myApp',[]); //定義了一個叫myApp的模塊 //定義控制器 app.controller('myController',function($scope){ $scope.add=function(){ $scope.z= parseInt($scope.x)+parseInt($scope.y); } }); </script> </head> <body ng-app="myApp" ng-controller="myController"> x:<input ng-model="x" > y:<input ng-model="y" > <button ng-click="add()">運算</button> 結果:{{z}} </body> </html> |
運行結果:
ng-click 是最常用的單擊事件指令,再點擊時觸發控制器的某個方法
1.3.6 循環數組
<html> <head> <title>入門小Demo-6 循環數據</title> <script src="angular.min.js"></script> <script> var app=angular.module('myApp',[]); //定義了一個叫myApp的模塊 //定義控制器 app.controller('myController',function($scope){ $scope.list= [100,192,203,434 ];//定義數組 }); </script> </head> <body ng-app="myApp" ng-controller="myController"> <table> <tr ng-repeat="x in list"> <td>{{x}}</td> </tr> </table> </body> </html> |
這里的ng-repeat指令用於循環數組變量。
運行結果如下:
1.3.7 循環對象數組
<html> <head> <title>入門小Demo-7 循環對象數組</title> <script src="angular.min.js"></script> <script> var app=angular.module('myApp',[]); //定義了一個叫myApp的模塊 //定義控制器 app.controller('myController',function($scope){ $scope.list= [ {name:'張三',shuxue:100,yuwen:93}, {name:'李四',shuxue:88,yuwen:87}, {name:'王五',shuxue:77,yuwen:56} ];//定義數組 }); </script> </head> <body ng-app="myApp" ng-controller="myController"> <table> <tr> <td>姓名</td> <td>數學</td> <td>語文</td> </tr> <tr ng-repeat="entity in list"> <td>{{entity.name}}</td> <td>{{entity.shuxue}}</td> <td>{{entity.yuwen}}</td> </tr> </table> </body> </html> |
運行結果如下:
1.3.8 內置服務
我們的數據一般都是從后端獲取的,那么如何獲取數據呢?我們一般使用內置服務$http來實現。注意:以下代碼需要在tomcat中運行。
<html> <head> <title>入門小Demo-8 內置服務</title> <meta charset="utf-8" /> <script src="angular.min.js"></script> <script> var app=angular.module('myApp',[]); //定義了一個叫myApp的模塊 //定義控制器 app.controller('myController',function($scope,$http){ $scope.findAll=function(){ $http.get('data.json').success( function(response){ $scope.list=response; } ); } }); </script> </head> <body ng-app="myApp" ng-controller="myController" ng-init="findAll()"> <table> <tr> <td>姓名</td> <td>數學</td> <td>語文</td> </tr> <tr ng-repeat="entity in list"> <td>{{entity.name}}</td> <td>{{entity.shuxue}}</td> <td>{{entity.yuwen}}</td> </tr> </table> </body> </html> |
建立文件 data.json
[ {"name":"張三","shuxue":100,"yuwen":93}, {"name":"李四","shuxue":88,"yuwen":87}, {"name":"王五","shuxue":77,"yuwen":56}, {"name":"趙六","shuxue":67,"yuwen":86} ] |
2.品牌列表的實現
2.1需求分析
實現品牌列表的查詢(不用分頁和條件查詢)效果如下:
2.2前端代碼
2.2.1拷貝資源
將“02靜態原型/運營商管理后台”下的頁面資源拷貝到web- manager下
其中plugins文件夾中包括了angularJS 、bootstrap、JQuery等常用前端庫,我們將在項目中用到
2.2.2引入JS
修改brand.html ,引入JS
<script type="text/javascript" src="../plugins/angularjs/angular.min.js"></script> |
2.2.3指定模塊和控制器
<body class="hold-transition skin-red sidebar-mini" ng-app="pinyougou" ng-controller="brandController"> |
ng-app 指令中定義的就是模塊的名稱
ng-controller 指令用於為你的應用添加控制器。
在控制器中,你可以編寫代碼,制作函數和變量,並使用 scope 對象來訪問。
2.2.4編寫JS代碼
var app=angular.module('pinyougou', []);//定義模塊 app.controller('brandController' ,function($scope,$http){ //讀取列表數據綁定到表單中 $scope.findAll=function(){ $http.get('../brand/findAll.do').success( function(response){ $scope.list=response; } ); } }); |
2.2.5循環顯示表格數據
<tbody> <tr ng-repeat="entity in list"> <td><input type="checkbox" ></td> <td>{{entity.id}}</td> <td>{{entity.name}}</td> <td>{{entity.firstChar}}</td> <td class="text-center"> <button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" >修改</button> </td> </tr> </tbody> |
2.2.6初始化調用
<body class="hold-transition skin-red sidebar-mini" ng-app="pinyougou" ng-controller="brandController" ng-init="findAll()"> |
3.品牌列表分頁的實現
3.1需求分析
在品牌管理下方放置分頁欄,實現分頁功能
3.2后端代碼
3.2.1 分頁結果封裝實體
在pojo工程中創建entity包,用於存放通用實體類,創建類PageResult
package entity; import java.util.List; /** * 分頁結果封裝對象 * @author Administrator * */ public class PageResult implements Serializable{ private Long total;//總記錄數 private List rows;//當前頁結果 public PageResult(Long total, List rows) { super(); this.total = total; this.rows = rows; } //getter and setter ..... } |
3.2.2 服務接口層
在interface的BrandService.java 增加方法定義
/** * 返回分頁列表 * @return */ public PageResult findPage(Integer pageNum, Integer pageSize); |
3.2.3 服務實現層
在service-sellerGoods的BrandServiceImpl.java中實現該方法
@Override public PageResult findPage(Integer pageNum, Integer pageSize) { PageHelper.startPage(pageNum, pageSize); Page<Brand> page= (Page<Brand>) brandMapper.selectByExample(null); return new PageResult(page.getTotal(), page.getResult()); } |
PageHelper為MyBatis分頁插件
3.2.4 控制層
在web- manager工程的BrandController.java新增方法
/** * 返回全部列表 * @return */ @RequestMapping("/findPage") public PageResult findPage(Integer page, Integer rows){ return brandService.findPage(page, rows); } |
3.3前端代碼
3.3.1 HTML
在brand.html引入分頁組件
<!-- 分頁組件開始 --> <script src="../plugins/angularjs/pagination.js"></script> <link rel="stylesheet" href="../plugins/angularjs/pagination.css"> <!-- 分頁組件結束 --> |
構建app模塊時引入pagination模塊
var app=angular.module('pinyougou',['pagination']);//定義品優購模塊 |
頁面的表格下放置分頁組件
<!-- 分頁 --> <tm-pagination conf="paginationConf"></tm-pagination> |
3.3.2 JS代碼
在brandController中添加如下代碼
//重新加載列表 數據 $scope.reloadList=function(){ //切換頁碼 調用下面findpage的functtion $scope.findPage( $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage); } //分頁控件配置 $scope.paginationConf = { currentPage: 1, totalItems: 0, itemsPerPage: 5, perPageOptions: [5,10, 20, 30, 40, 50], onChange: function(){ $scope.reloadList();//重新加載 } }; //分頁 $scope.findPage=function(page,rows){ $http.get('../brand/findPage.do?page='+page+'&rows='+rows).success( function(response){ $scope.list=response.rows; $scope.paginationConf.totalItems=response.total;//更新總記錄數 } ); } |
在頁面的body元素上去掉ng-init指令的調用
paginationConf 變量各屬性的意義:
currentPage:當前頁碼
totalItems:總條數
itemsPerPage:每頁默認顯示多少條記錄
perPageOptions:頁碼選項
onChange:更改頁面時觸發事件
4.增加品牌
4.1需求分析
實現品牌增加功能
4.2后端代碼
4.2.1 服務實現層
在cn.itcast.core.service的BrandServiceImpl.java實現該方法
//添加 public void add(Brand brand){ brandDao.insertSelective(brand); } |
4.2.2 執行結果封裝實體
在pojo的entity包下創建類Result.java
/** * 返回結果封裝 * @author Administrator * */ public class Result implements Serializable{ /** * */ private static final long serialVersionUID = 1L;
private boolean flag; private String message; public Result(boolean flag, String message) { super(); this.flag = flag; this.message = message; } |
4.2.4 控制層
在manager的BrandController.java中新增方法
/** * 增加 * @param brand * @return */ @RequestMapping("/add") public Result add(@RequestBody Brand brand){ try { brandService.add(brand); return new Result(true, "增加成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "增加失敗"); } } |
4.3前端代碼
4.3.1 JS代碼
//保存 $scope.save=function(){ $http.post('../brand/add.do',$scope.entity ).success( function(response){ if(response.flag){ //重新查詢 $scope.reloadList();//重新加載 }else{ alert(response.message); } } ); } |
4.3.2 HTML
綁定表單元素,我們用ng-model指令,綁定按鈕的單擊事件我們用ng-click
<div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button> <h3 id="myModalLabel">品牌編輯</h3> </div> <div class="modal-body"> <table class="table table-bordered table-striped" width="800px"> <tr> <td>品牌名稱</td> <td><input class="form-control" ng-model="entity.name" placeholder="品牌名稱" > </td> </tr> <tr> <td>首字母</td> <td><input class="form-control" ng-model="entity.firstChar" placeholder="首字母"> </td> </tr> </table> </div> <div class="modal-footer"> <button class="btn btn-success" data-dismiss="modal" aria-hidden="true" ng-click="save()">保存</button> <button class="btn btn-default" data-dismiss="modal" aria-hidden="true">關閉</button> </div> </div> </div> |
為了每次打開窗口沒有遺留上次的數據,我們可以修改新建按鈕,對entity變量進行清空操作
<button type="button" class="btn btn-default" title="新建" data-toggle="modal" data-target="#editModal" ng-click="entity={}"><i class="fa fa-file-o"></i> 新建</button> |
5.修改品牌
5.1 需求分析
點擊列表的修改按鈕,彈出窗口,修改數據后點“保存”執行保存操作
5.2 后端代碼
5.2.1 服務實現層
在sellergoods的BrandServiceImpl.java新增方法實現
//修改 public void update(Brand brand){ brandDao.updateByPrimaryKeySelective(brand); } //查詢一個品牌 public Brand findOne(Long id){ return brandDao.selectByPrimaryKey(id); } |
5.2.3 控制層
在manager-web的BrandController.java新增方法
//修改 @RequestMapping(value = "/update.do") public Result update(@RequestBody Brand brand){ try { brandService.update(brand); return new Result(true,"修改成功"); } catch (Exception e) { // TODO: handle exception return new Result(false,"修改失敗"); } } //查詢一個品牌 @RequestMapping(value = "/findOne.do") public Brand findOne(Long id){ return brandService.findOne(id); } |
5.3 前端代碼
5.3.1 實現數據查詢
增加JS代碼
//查詢實體 $scope.findOne=function(id){ $http.get('../brand/findOne.do?id='+id).success( function(response){ $scope.entity= response; 因為雙向綁定 直接把查詢到的brand賦值給entity就可以
} ); } |
修改列表中的“修改”按鈕,調用此方法執行查詢實體的操作
<button type="button" class="btn bg-olive btn-xs" data-toggle="modal" data-target="#editModal" ng-click="findOne(entity.id)" >修改</button> |
5.3.2 保存數據
修改JS的save方法
//保存 $scope.save=function(){ var methodName='add';//方法名稱 if($scope.entity.id!=null){//如果有ID methodName='update';//則執行修改方法 } $http.post('../brand/'+ methodName +'.do',$scope.entity ).success( function(response){ if(response.success){ //重新查詢 $scope.reloadList();//重新加載 }else{ alert(response.message); } } ); } |
6.刪除品牌
6.1 需求分析
點擊列表前的復選框,點擊刪除按鈕,刪除選中的品牌。
6.2 后端代碼
6.2.1 服務接口層
在interface的BrandService.java接口定義方法
/** * 批量刪除 * @param ids */ public void delete(Long [] ids); |
6.2.2 服務實現層
在sellergoods的BrandServiceImpl.java實現該方法
/** * 批量刪除 */ @Override public void delete(Long[] ids) { for(Long id:ids){ brandDao.deleteByPrimaryKey(id); } } |
6.2.3 控制層
在manager的BrandController.java中增加方法
/** * 批量刪除 * @param ids * @return */ @RequestMapping("/delete") public Result delete(Long [] ids){ try { brandService.delete(ids); return new Result(true, "刪除成功"); } catch (Exception e) { e.printStackTrace(); return new Result(false, "刪除失敗"); } } |
6.3 前端代碼
6.3.1 JS
主要思路:我們需要定義一個用於存儲選中ID的數組,當我們點擊復選框后判斷是選擇還是取消選擇,如果是選擇就加到數組中,如果是取消選擇就從數組中移除。在點擊刪除按鈕時需要用到這個存儲了ID的數組。
這里我們補充一下JS的關於數組操作的知識
(1) 數組的push方法:向數組中添加元素
(2) 數組的splice方法:從數組的指定位置移除指定個數的元素 ,參數1為位置 ,參數2位移除的個數
(3)復選框的checked屬性:用於判斷是否被選中
$scope.selectIds=[];//選中的ID集合 //更新復選 $scope.updateSelection = function($event, id) { if($event.target.checked){//如果是被選中,則增加到數組 $scope.selectIds.push( id); }else{ var idx = $scope.selectIds.indexOf(id); $scope.selectIds.splice(idx, 1);//刪除 splice 參數1:刪除哪個id 參數2:刪除幾個 } } //刪除 $scope.dele=function(){ $http.get("/brand/delete.do?ids=" + $scope.selectedIds).success( function(response){ if(response.flag){ $scope.reloadList(); $scope.selectedIds = []; }else{ alert(response.message); } } ); } |
6.3.2 HTML
(1)修改列表的復選框
<tr ng-repeat="entity in list"> <td><input type="checkbox" ng-click="updateSelection($event,entity.id)"></td> |
(2)修改刪除按鈕
<button type="button" class="btn btn-default" title="刪除" ng-click="dele()"><i class="fa fa-trash-o"></i> 刪除</button> |
7.品牌條件查詢
如果沒查詢到結果 是因為分頁控件默認調用的是 reloadlist() 所以相當查詢了兩次 第一次:查詢的是分頁條件查詢,第二次查的reloadlist() 的查詢所有
7.1需求分析
實現品牌條件查詢功能,輸入品牌名稱、首字母后查詢,並分頁。
7.2后端代碼
7.2.1 服務實現層
在sellergoods-service工程BrandServiceImpl.java實現該方法
// 根據條件查詢分頁對象 public PageResult search(Integer pageNum, Integer pageSize, Brand brand) { // Mybatis分頁插件 PageHelper.startPage(pageNum, pageSize); // 判斷是否有條件需要查詢 BrandQuery brandQuery = new BrandQuery(); if (null != brand) { Criteria createCriteria = brandQuery.createCriteria(); if (null != brand.getName() && !"".equals(brand.getName().trim())) { createCriteria.andNameLike("%" + brand.getName().trim() + "%"); } if(null != brand.getFirstChar() && !"".equals(brand.getFirstChar().trim())){ createCriteria.andFirstCharEqualTo(brand.getFirstChar().trim()); } } Page<Brand> page = (Page<Brand>) brandDao.selectByExample(brandQuery); return new PageResult(page.getTotal(), page.getResult()); } |
7.2.2 控制層
在manager的BrandController.java增加方法
//根據條件查詢分頁對象 @RequestMapping(value = "/search.do") public PageResult search(Integer pageNum,Integer pageSize,@RequestBody(required=false) 不寫參數就報錯 如果為trueBrand brand){ return brandService.search(pageNum, pageSize, brand); } |
7.3前端代碼
修改manager的
//根據條件查詢分頁對象 $scope.search=function(pageNum,pageSize){ $http.post("/brand/search.do?pageNum=" + pageNum + "&pageSize=" + pageSize,$scope.searchEntity).success( function(response){ $scope.paginationConf.totalItems=response.total; $scope.list=response.rows; }
); } |
修改reloadList方法
//刷新列表 $scope.reloadList=function(){ $scope.search( $scope.paginationConf.currentPage, $scope.paginationConf.itemsPerPage); } |
7.4 HTML
<div class="box-tools pull-right"> <div class="has-feedback"> //searchEntity 是用作提交的 與上面的entity不能相同 品牌名稱:<input type="text" ng-model="searchEntity.name"> 品牌首字母:<input type="text" ng-model="searchEntity.firstChar"> <input class="btn btn-default" ng-click="reloadList()" type="button" value="查詢"> //調用reloadlist() 是為了他調用了serch()里面有pagenum和pagesize </div> </div> |