您的位置:首页 > Web前端 > AngularJS

AngularJS动态绑定ng-options的ng-model

2016-01-26 21:52 609 查看
http://www.it165.net/pro/html/201304/5564.html

什么情况下会需要动态绑定 ng-model 呢?若你的数据结构长得像是下面这样:

 

view
sourceprint?

1.
var
 
Classes
= [


2.
{


3.
"Name"
 
"温度
"
 
,


4.
"Options"
 
:
[ 
"Cold"
 
"Hot"
 
"Normal"
 
]},


5.
{


6.
"Name"
 
"份量
"
 
,


7.
"Options"
 
:
[ 
"Big"
 
"Middle"
 
"Small"
 
]}


8.
];


此时你需要用 ng-repeat 将数据展开,并且将 Options 个别设置为 ng-options 的数据,此时就须要动态去绑定 ng-model,那么该如何绑呢?你可能需要在你的 Controller 底下加上一个变量来做这些动态呈现的 ng-options 的数据指定。 www.it165.net

说的这么抽象,不如马上来看 Code 吧。

 

view
sourceprint?

01.
<!--
DOM -->


02.
 

03.
<div 
class
 
=
"container"
>


04.
 

05.
<div
ng-repeat= 
"class
in classes"
>


06.
 

07.
{{
class
.Name}}


08.
 

09.
<select
ng-model=
"SelectdCollection[class.Name]"
 
ng-options=
"option
for option in class.Options"
 
></select>


10.
 

11.
</div>


12.
 

13.
<a 
class
=
"btn
btn-success"
 
ng-click= 
"submit()"
>送出
</a>


14.
 

15.
</div>


16.
 

17.
 

18.
 

19.
//
Javascript


20.
 

21.
function
 
DemoController($scope){


22.
 

23.
$scope.classes
= [


24.
 

25.
{


26.
 

27.
"Name"
"温度
"
,


28.
 

29.
"Options"
 
:
[
"Cold"
 
"Hot"
"Normal"
]


30.
 

31.
},


32.
 

33.
{


34.
 

35.
"Name"
"份量
"
,


36.
 

37.
"Options"
 
:
[
"Big"
 
"Middle"
 
"Small"
 
]


38.
 

39.
}


40.
 

41.
];


42.
 

43.
$scope.SelectdCollection
= {};


44.
 

45.
$scope.submit
= 
function
()
{


46.
 

47.
console
.log($scope. SelectdCollection);


48.
 

49.
};


50.
 

51.
}


在这一小段程序代码中,我们在 DemoController 里面宣告了 $scope.SelectdCollection,这就是刚才提到的承接动态 ng-model 值的对象,这边定义了一个按钮,按下之后可以及时把动态呈现的 ng-options 所选的值丢到开发者工具的 console 去。

实际画面会是长这样。

 



 

按下送出可以在开发者工具看到如下的 log,成功取得资料。

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: