ng-options属性可以在表达式中使用数组或对象来自动生成一个select中的option列表。
as前面为真实值(input或下拉框的value值),后面为显示值。
ng-options与ng-repeat很相似,很多时候可以用ng-repeat来代替ng-options。但是ng-options提供了一些好处,例如减少内存提高速度,以及提供选择框的选项来让用户选择。
ng-options="item.id as item.name for item in selectItemCat1List"
item in selectItemCat1List是对数组进行遍历
item.id as item.name for设置option选项的value值为item.id显示值为item.name
$watch方法用于监控某个变量的值,当被监控的值发生变化,就自动执行相应的函数。
修改goods_edit.html中二级分类下拉框
$scope.$watch("entity.goods.category1Id",function (newVal,oldVal) {
itemCatService.findByParentId(newVal).success(
function (response) {
$scope.itemCatList2 = response;
//清空三级分类
$scope.itemCatList3 = [];
})
})
第一个参数表示监听的对象,第二个参数表示监听对象发生变化之后,执行的操作
也就是说当我们用切换下拉框的选项时,ng-model绑定的对象获得的值实际是分类的id,当$watch函数监听到对象值得更改时就会执行方法函数
完整代码
goodsController.js
//获取一级分类
$scope.selectItemCat1List = function (pid) {
itemCatService.findByParentId(pid).success(
function (response) {
$scope.itemCatList1 = response;
})
}
//监听1级分类的变化,得到2级分类
//第一个参数表示监听的对象
//第二个参数表示监听对象发生变化之后,执行的操作
$scope.$watch("entity.goods.category1Id",function (newVal,oldVal) {
itemCatService.findByParentId(newVal).success(
function (response) {
$scope.itemCatList2 = response;
//清空三级分类
$scope.itemCatList3 = [];
})
})
//读取三级分类
$scope.$watch("entity.goods.category2Id",function (newVal,oldVal) {
itemCatService.findByParentId(newVal).success(
function (response) {
$scope.itemCatList3 = response;
})
})
itemCatService.js
this.findByParentId = function (id) {
return $http.get('../itemCat/findByParentId?id='+id);
}
html页面选择框代码
<div class="col-md-10 data">
<table>
<tr>
<td>
<select class="form-control" ng-model="entity.goods.category1Id" ng-options="item.id as item.name for item in itemCatList1"></select>
</td>
<td>
<select class="form-control select-sm" ng-model="entity.goods.category2Id" ng-options="item.id as item.name for item in itemCatList2"></select>
</td>
<td>
<select class="form-control select-sm" ng-model="entity.goods.category3Id" ng-options="item.id as item.name for item in itemCatList3"></select>
</td>
<td>
模板ID:19
</td>
</tr>
</table>
</div>