Angular--ng-options
- 用途
- 下拉菜单组成
- 适用情形一,普通数组
- 适用情形二(数组嵌套对象)
- 适用情形三(普通对象)
学习资源推荐:
https://blog.csdn.net/qq_42813491/article/details/90213353
用途
ng-options属性特别的好用,可以智能的从控制器中取值当前的值做选项,用在下拉菜单里边
下拉菜单组成
- 组成就两个东西,一个是显示的东西,叫label,一个是要提交的值,叫value
- 以打折为例,呈递到界面的选项是五折六折七折,真正提交的是0.5,0.6,0.7
<select><option value&#61;"0.5">五折option><option value&#61;"0.6">六折option><option value&#61;"0.7">七折option>select>
适用情形一&#xff0c;普通数组
<html lang&#61;"en" ng-app&#61;"app">
<head><meta charset&#61;"UTF-8"><title>Angular--ng-optionstitle><script type&#61;"text/Javascript" src&#61;"js/lib/angular/angular.min.js">script>
head>
<body><div ng-controller&#61;"MainCtrl as mainctrl"><select ng-model&#61;"mainctrl.value" ng-options&#61;"item for item in mainctrl.arr" >select>{{mainctrl.value}}div><script type&#61;"text/Javascript">var app &#61; angular.module("app",[]);app.controller("MainCtrl",[function(){this.value&#61;"东";this.arr&#61;["东","西","南","北"];}]);script>
body>
html>
效果图
适用情形二&#xff08;数组嵌套对象&#xff09;
<html lang&#61;"en" ng-app&#61;"app">
<head><meta charset&#61;"UTF-8"><title>Angular--ng-optionstitle><script type&#61;"text/Javascript" src&#61;"js/lib/angular/angular.min.js">script>
head>
<body><div ng-controller&#61;"MainCtrl as mainctrl"><select ng-model&#61;"mainctrl.value" ng-options&#61;"item.sid as item.name for item in mainctrl.arr" >select>{{mainctrl.value}}div><script type&#61;"text/Javascript">var app &#61; angular.module("app",[]);app.controller("MainCtrl",[function(){this.value&#61;"001";this.arr &#61; [{"sid" : "001" , "name" : "冷月心"},{"sid" : "002" , "name" : "莫山山"},{"sid" : "003" , "name" : "叶红鱼"}];}]);script>
body>
html>
- 解释 ng-options&#61;“item.sid as item.name for item in mainctrl.arr”
- item.sid 指定当前项的value值&#xff0c;也就是要提交的值
- item.name指定当前项的label值&#xff0c;也就是要消失在下拉框的值
- item 遍历项
- mainctrl.arr 要遍历的数组
适用情形三&#xff08;普通对象&#xff09;
<html lang&#61;"en" ng-app&#61;"app">
<head><meta charset&#61;"UTF-8"><title>Angular--ng-optionstitle><script type&#61;"text/Javascript" src&#61;"js/lib/angular/angular.min.js">script>
head>
<body><div ng-controller&#61;"MainCtrl as mainctrl"><select ng-model&#61;"mainctrl.value" ng-options&#61;"value as key for (key,value) in mainctrl.arr" >select>{{mainctrl.value}}div><script type&#61;"text/Javascript">var app &#61; angular.module("app",[]);app.controller("MainCtrl",[function(){this.value&#61;"粤";this.arr &#61; {"广东" : "粤","北京" : "京","上海" : "沪","湖北" : "鄂","河南" : "豫"};}]);script>
body>
html>
- value as key for (key,value) in mainctrl.arr
- value 提交的值
- key 显示的值