AngularJS實例教程

實例代碼前臺採用目前比較流行的AngularJS, 後臺爲spring而且能夠對數據進行查詢與保存, 代碼實現了一個購物車功能:<1>添加商品,對購買的商品進行編輯,包括:產品編號,產品名稱,購買數量,產品單價<2>商品數量修改時,總價格動態變化<3>提交商品信息而且進行後臺保存javascript

實例下載:http://www.wisdomdd.cn/Wisdom/resource/articleDetail.htm?resourceId=42css

Demo中使用的工具能夠在百度雲下載:html

Eclipse: http://pan.baidu.com/s/1c4f5zojava

Tomcat: http://pan.baidu.com/s/1c1KGqPEmysql

Maven: http://pan.baidu.com/s/1kVeKHDlangularjs

MySql服務器: http://pan.baidu.com/s/1b7ThBgspring

MySql客戶端(sqlyog): http://pan.baidu.com/s/1hs5Vmbqsql

JDK1.7: http://pan.baidu.com/s/1pLBMCHH數據庫

爲了更好的學習,下面先簡單介紹下AngularJsjson

1.AngularJS

AngularJS是一個開源Web應用程序框架。它最初是由MISKO Hevery和Adam Abrons於2009年開發。如今是由谷歌維護。它的最新版本是1.3.14。項目中對AngularJS進行了集成,下載demo後能夠查看, 也能夠到官網: https://angularjs.org/ 進行下載

1.1AngularJs開發js庫的引入:

1

<script type="text/javascript" src="<%=contextPath%>/jsLib/angular/angularjs.js"></script>

1.2AngularJs在html中的申明

<div ng-app='shopCarApp' ng-controller="carShopController">

一個html頁面中只能有一個ng-app, 卻能夠有多個ng-controller

js中對ng-app和ng-controller的初始化

var appShopCar = angular.module("shopCarApp", [], function($provide){ });
appShopCar.controller("carShopController", function ($scope, $http) { });

1.3數據雙向綁定:

AngularJs最大的特性即是雙向綁定,也就是Js中的數據變更時,能夠實時動態將數據結果根據預先寫好的規則反應到界面上

好比: $scope.data = 1;

<td>{{item.data}}</td> 則頁面中應該顯示爲1;

若是$scope.data被動態修改成 2,頁面會動態顯示爲 2

雙向綁定帶來的好處是開發人員只須要專一於業務邏輯的處理,頁面上元素的變化不須要過多的關注與處理

1.4數據通信:

POST方法:

AngularJS實例教程

$http.post("/AngularJs/goods/saveGoods.htm", //後臺URL地址 { goodsList : JSON.stringify($scope.carShop), //請求參數 }) .success(function (data, header, config, status) { if(data.stateCode == 0){ //結果處理 alert(data.desc); } }) .error(function (data, header, config, status) { console.log(data); });

AngularJS實例教程

GET方法:

AngularJS實例教程

$http.get("/AngularJs/user/get.htm", //後臺URL地址{params: {param: $scope.param}}) //請求參數 .success(function (data, header, config, status) { console.log(data); //結果處理 }) .error(function (response) { console.log(response); });

AngularJS實例教程

好了,有關更多的AngularJs的信息能夠到網上進行查閱

2 運行效果

啓動項目,訪問地址: http://localhost:8080/AngularJs/jsp/shopCar.jsp

效果圖:

AngularJS實例教程

2.1 點擊清空購物車,則商品會被所有清空

2.2 點擊添加商品按鈕,彈出商品編輯對話框,編輯產品編輯,產品名稱,購買數量,產品單價

AngularJS實例教程

2.3 點擊提交商品按鈕,將前臺商品信息傳到後臺進行保存

2.4 點擊購買數量上的+-按鈕時,商品數量會相應的+1,-1, 對應的產品總價進行變化,總購買價也會進行變化

3. 代碼介紹:

代碼框架如圖:

AngularJS實例教程

3.1 數據庫表:

建立數據表:t_goods

AngularJS實例教程

CREATE TABLE `t_goods` ( `GoodsId` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '商品主鍵', `GoodsNo` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品編號', `GoodsName` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品名字', `GoodsNum` int(10) DEFAULT NULL COMMENT '購買數量', `GoodsPrice` decimal(10,2) DEFAULT NULL COMMENT '商品單價', PRIMARY KEY (`GoodsId`)) ENGINE=InnoDB AUTO_INCREMENT=47 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci

AngularJS實例教程

3.2 修改jdbc.properties鏈接數據庫的用戶名與密碼

url=jdbc:mysql://127.0.0.1:3306/t_angular?characterEncoding=utf-8&allowMultiQueries=true#url=jdbc:mysql://www.ad186.com:3306/hctl?characterEncoding=utf-8username=rootpassword=ajqnhwvia

3.2 前臺代碼

3.2.1 前臺代碼使用了bootstrap進行效果上的渲染, bootstrap下載: http://v3.bootcss.com/

3.2.2 商品列表頁面代碼:

AngularJS實例教程

<body ng-app='shopCarApp' ng-controller="carShopController"><div class="container"><table class="table" ng-show="carShop.length"><thead><tr><th>產品編號</th><th>產品名字</th><th>購買數量</th><th>產品單價</th><th>產品總價</th><th>操做</th></tr></thead><tbody><tr ng-repeat="item in carShop"><td>{{item.goodsNo}}</td><td>{{item.goodsName}}</td><td><form class="form-inline"><div class="form-group"><button type="button" ng-click="reduce(item.goodsNo)" class="btn btn-primary">-</button><input type="text" class="form-control" id="exampleInputName2" value="{{item.goodsNum}}" ng-model="item.goodsNum" ><button type="button" ng-click="add(item.goodsNo)" class="btn btn-primary">+</button></div></form></td><td>{{item.goodsPrice}}</td><td>{{item.goodsPrice * item.goodsNum}}</td><td><button type="button" ng-click="remove(item.goodsNo)" class="btn btn-danger">移除</button></td></tr><tr><td></td><td></td><td></td><td></td><td colspan="2"></td></tr></tbody></table><b>總購買價:</b>{{totalPrice()}} &nbsp;&nbsp;&nbsp;<b>總購買數量:</b>{{totalQuantity()}}<br><p ng-show="!carShop.length">您的購物車爲空</p><button type="button" ng-click="clearShop()" class="btn btn-danger">清空購物車</button><button type="button" ng-click="addCarShop()" class="btn btn-danger">添加商品</button><button type="button" ng-click="saveGoods()" class="btn btn-danger">提交商品</button></div>

AngularJS實例教程

3.3 商品編輯框代碼:

AngularJS實例教程

<!-- 添加商品 --><div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"><div class="modal-header"><h4 class="modal-title" id="myModalLabel" style="float: left;">新增商品</h4><button type="button" class="close closeModel" aria-label="Close" onClick="closeMod()"><span aria-hidden="true">&times;</span><tton></div><form id="goodsInfoForm" class="form-horizontal" role="form" style="margin-left: 30px; margin:30px;"><div class="form-group"><label for="goodsNo" class="col-sm-3 control-label"><span class="star_tip">*</span>產品編號:</label><div class="col-sm-8"><input ng-model="goods.goodsNo" type="text" class="form-control" id="goodsNo" name="goodsNo" value='1111' placeholder="產品編號"/></div></div><div class="form-group"><label for="goodsName" class="col-sm-3 control-label"><span class="star_tip">*</span>產品名稱:</label><div class="col-sm-8"><input ng-model="goods.goodsName" type="text" class="form-control" id="goodsName" name="goodsName" value='iphone8' placeholder="產品名稱"></div></div><div class="form-group"><label for="goodsNum" class="col-sm-3 control-label"><span class="star_tip">*</span>購買數量:</label><div class="col-sm-8"><input ng-model="goods.goodsNum" type="text" class="form-control" id="goodsNum" name="goodsNum" value='12' placeholder="購買數量"></div></div><div class="form-group"><label for="goodsPrice" class="col-sm-3 control-label"><span class="star_tip">*</span>產品單價:</label><div class="col-sm-8"><input ng-model="goods.goodsPrice" type="text" class="form-control" id="goodsPrice" name="goodsPrice" value='12' placeholder="產品單價"></div></div><div class="modal-footer" style="text-align:center;"><button type="button" class="btn btn-primary" id="save" ng-click="addGoods()">保存<tton><button type="button" class="btn btn-default closeModel" onClick="closeMod()">關閉<tton></div></form></div></div></div>

AngularJS實例教程

3.4 js邏輯代碼處理

包括:AngularJs模塊初始化,商品信息的加載,商品信息的增長,刪除,提交

AngularJS實例教程

var appShopCar = angular.module("shopCarApp", [], function($provide){// 從服務器上獲取初始化數據$provide.service('carShop',function($http){ var carShop = []; return carShop; })});appShopCar.controller("carShopController", function ($scope, $http) {console.log('加載 carShopController');$http.get("/AngularJs/goods/getGoods.htm") .success(function (data, header, config, status) { console.log(data); $scope.carShop = data.data; }) .error(function (response) { console.log(response); }); /** * 計算購物總價 */ $scope.totalPrice = function () { var total = 0; angular.forEach($scope.carShop, function (item) { total += item.goodsNum * item.goodsPrice; }) return total; } /** * 計算總購買數 */ $scope.totalQuantity = function () { var total = 0; angular.forEach($scope.carShop, function (item) { total += parseInt(item.goodsNum); }) return total; } /** * 找一個元素的索引 */ var findIndex = function (goodsNo) { var index = -1; angular.forEach($scope.carShop, function (item, key) { if (item.goodsNo === goodsNo) { index = key; return; } }); return index; } /** * 爲某個產品添加一個數量 */ $scope.add = function (goodsNo) { var index = findIndex(goodsNo); if (index !== -1) { ++$scope.carShop[index].goodsNum; } } /** * 爲某個產品減小一個數量 */ $scope.reduce = function (goodsNo) { var index = findIndex(goodsNo); if (index !== -1) { var item = $scope.carShop[index]; if(item.goodsNum > 1){ --item.goodsNum; }else{ var returnKey = confirm('是否從購物車內刪除該產品!'); if(returnKey){ $scope.remove(goodsNo); } } } } /** * 移除一項 */ $scope.remove = function (goodsNo) { var index = findIndex(goodsNo); // 若是找到了那個itemif (index !== -1) { $scope.carShop.splice(index, 1); } // 自動作髒檢查 } /** * 清空購物車 */ $scope.clearShop = function(){ $scope.carShop.length = 0; } /** * 添加商品 */ $scope.addCarShop = function(){ addCarShop(); } /** * 保存商品 */ $scope.addGoods = function() { //$('#goodsInfoForm').bootstrapValidator('validate');var bSuccess = $('#goodsInfoForm').data("bootstrapValidator").isValid(); if(bSuccess){ console.log($scope.goods); console.log(JSON.stringify($scope.goods)); /*$scope.goods.goodsNum = 4; $scope.goods.goodsPrice = 23000;*/ var goods = {}; goods.goodsNo = $scope.goods.goodsNo; goods.goodsName = $scope.goods.goodsName; goods.goodsNum = $scope.goods.goodsNum; goods.goodsPrice = $scope.goods.goodsPrice; $scope.carShop.push(goods); closeMod(); } } /** * 提交商品 */ $scope.saveGoods = function(){ if($scope.carShop.length == 0){ alert('沒有商品提交'); return; } var postCfg = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, transformRequest: function (data) { return $.param(data); } }; $http.post("/AngularJs/goods/saveGoods.htm", { goodsList : JSON.stringify($scope.carShop), }, postCfg) .success(function (data, header, config, status) { if(data.stateCode == 0){ alert(data.desc); } }) .error(function (data, header, config, status) { console.log(data); }); }});$(function () {//校驗form表單//校驗bootstrap form表單$('#goodsInfoForm') .bootstrapValidator({ message: 'This value is not valid', feedbackIcons: { valid: 'glyphicon glyphicon-ok', invalid: 'glyphicon glyphicon-remove', validating: 'glyphicon glyphicon-refresh' }, fields: { 'goodsNo': { validators: { notEmpty: { message: '產品編號不能爲空' }, stringLength: { min: 4, message: '產品編號最少4位' }, numeric: { message: '稅額只能輸入數字' } } }, 'goodsName': { validators: { notEmpty: { message: '產品名稱不能爲空' } } }, 'goodsNum': { validators: { notEmpty: { message: '購買數量不能爲空' }, numeric: { message: '稅額只能輸入數字' } } }, 'goodsPrice': { validators: { notEmpty: { message: '產品單價不能爲空' }, numeric: { message: '稅額只能輸入數字' } } } } }).on('success.form.bv', function(e) { alert('aaaaa'); });});/*** 清除控件元素中的內容 */function formClear() {}//添加數據function addCarShop() { formClear();//這個modal函數是bootstrap.js中的函數$("#myModal").modal("show"); }/**關閉窗口*/function closeMod(){//重置form表單$('#goodsInfoForm').data('bootstrapValidator').resetForm(true);$("#myModal").modal("hide");}

AngularJS實例教程

3.5 後臺處理, 前臺與後臺通信的數據格式爲json

保存商品信息

AngularJS實例教程

@RequestMapping("/saveGoods.htm") @ResponseBody public Result saveGoods(ModelMap map, HttpServletRequest request) { String strGoodsList = request.getParameter("goodsList"); List<Goods> lstGoods = JSON.parseArray(strGoodsList, Goods.class); Result result = new Result(); result.setStateCode("0"); result.setDesc("提交商品成功"); int nCount = goodsService.insertBatchGoods(lstGoods); return result; }

AngularJS實例教程

查詢商品信息

AngularJS實例教程

@RequestMapping("/getGoods.htm") @ResponseBody public Result getGoods(ModelMap map, HttpServletRequest request) { Goods goods = new Goods(); List<Goods> lstGoods = goodsService.selectGoods(goods); Result result = new Result(); result.setStateCode("0"); result.setDesc("查詢成功"); result.setData(lstGoods); return result; 
相關文章
相關標籤/搜索