在商品录入界面实现商品分类的选择(三级分类)效果如下:
当用户选择一级分类后,二级分类列表要相应更新,当用户选择二级分类后,三级列表要相应更新。
在 pinyougou-shop-web 工程中创建 ItemCatController.
@RestController
@RequestMapping("/itemCat")
public class ItemCatController {
@Reference
private ItemCatService itemCatService;
/**
* 根据上级 ID 查询列表
* @param parentId
* @return
*/
@RequestMapping("/findByParentId")
public List findByParentId(Long parentId){
return itemCatService.findByParentId(parentId);
}
/**
* 获取实体
* @param id
* @return
*/
@RequestMapping("/findOne")
public TbItemCat findOne(Long id){
return itemCatService.findOne(id);
}
}
创建 item_catService.js
//服务层
app.service('itemCatService',function($http){
//根据上级 ID 查询下级列表
this.findByParentId=function(parentId){
return $http.get('../itemCat/findByParentId.do?parentId='+parentId);
}
//查询实体
this.findOne=function(id){
return $http.get('../item/findOne.do?id='+id);
}
});
修改 goodsController.js,引入 itemCatService
//控制层
app.controller('goodsController' ,function($scope,$controller,goodsService,itemCatService ){
修改 goods_edit.html,添加引用
在 goodsController 增加代码
//读取一级分类
$scope.selectItemCat1List=function(){
itemCatService.findByParentId(0).success(
function(response){
$scope.itemCat1List=response;
}
);
}
修改 goods_edit.html 一级分类下拉选择框
注意:ng-options 是新的指令,用来循环获取下拉列表.
在 goodsController 增加代码:
//读取二级分类
$scope.$watch('entity.goods.category1Id', function(newValue, oldValue) {
//根据选择的值,查询二级分类
itemCatService.findByParentId(newValue).success(
function(response){
$scope.itemCat2List=response;
}
);
});
$watch 用于监控某个变量的值,当被监控的值发生变化,就自动执行相应的函数。
修改 goods_edit.html 中二级分类下拉框
在 goodsController 增加代码
//读取三级分类
$scope.$watch('entity.goods.category2Id', function(newValue, oldValue) {
//根据选择的值,查询二级分类
itemCatService.findByParentId(newValue).success(
function(response){
$scope.itemCat3List=response;
}
);
});
修改 goods_edit.html 中三级分类下拉框
在 goodsController 增加代码
//三级分类选择后 读取模板 ID
$scope.$watch('entity.goods.category3Id', function(newValue, oldValue) {
itemCatService.findOne(newValue).success(
function(response){
$scope.entity.goods.typeTemplateId=response.typeId; //更新模板 ID
}
);
});
在 goods_edit.html 显示模板 ID
模板 ID:{{entity.goods.typeTemplateId}}