[英]How can I get an object from select element via AngularJS
I have select html element like this: 我选择了这样的 html元素:
<select required="" ng-model="studentGroup">
<option value="" selected="">--select group--</option>
<option value="1">java 15-1</option>
<option value="2">java 15-2</option>
<option value="3">java 15-3</option>
</select>
I want to get an object - studentGroup: {groupId:'1', groupName:'java 15-1'}
when first option is selected(for example), where groupId - 'value' attribute of selected option, groupName - 'text' attribute. 我想得到一个对象 -
studentGroup: {groupId:'1', groupName:'java 15-1'}
当选择第一个选项时(例如),其中groupId - 所选选项的'value'属性, groupName - 'text '属性。
How can I do this using AngularJS ? 我怎么能用AngularJS做到这一点?
UPDATE: 更新:
It was solved as below: 它解决如下:
<select ng-options="group.groupName for group in ctrl.groupList track by group.groupId" ng-model="ctrl.student.studentGroup"></select>
Selected studentGroup object: {{ctrl.studentGroup}}
where ctrl - my controller with groupList Array with studentGroup objects; 其中ctrl - 我的控制器与groupList数组与studentGroup对象; studentGroup - selected object as I wanted.
studentGroup - 我想要的选定对象。
This can be achieved with angular's ng-options directive. 这可以通过angular的ng-options指令实现。 By declaring values for the select drop down in an array and iterating it with the help of ng-options directive
通过在数组中声明选择下拉列表的值并在ng-options指令的帮助下迭代它
$scope.studentGroups = [{
id: 1,
groupName: 'java 15-1'
}, {
id: 2,
groupName: 'java 15-2'
}];
<select ng-options="studentGroup as studentGroup.groupName for studentGroup in studentGroups track by studentGroup.id" ng-model="selected"></select>
How about that : 那个怎么样 :
$scope.studentGroup = [
{ groupId: 1, groupName: 'java 15-1'},
{ groupId: 2, groupName: 'java 15-2'},
{ groupId: 3, groupName: 'java 15-3'},
{ groupId: 4, groupName: 'java 15-4'}
];
<select
ng-options="p.groupId + ' ' + p.groupName for p in studentGroup" ng-model="selectedPerson">
</select>
Hello I have made an example the uses a <select>
element , json array object to load values , custom directive that listens change events and calls controller function to give the selected object . 您好我已经做了一个例子 ,使用
<select>
元素 , json数组对象加载值 , 自定义指令侦听更改事件并调用控制器函数来给出所选对象 。
plunkr example: http://plnkr.co/edit/iCS0blQjceA4tIIb8bUV?p=preview plunkr示例: http ://plnkr.co/edit/iCS0blQjceA4tIIb8bUV?p = preview
{{selectedObj}}
<div class="col-xs-12 form-control"
change-hall="filterHall(value)"
items=items
event-halls-list
model='selectedObj'>
</div>
.directive('eventHallsList', function($timeout, $log, $http, $compile) {
return {
restrict: 'AE',
replace: true,
scope: {
changeHall: '&',
items: '=',
model: '='
},
templateUrl: 'mytemplate.tpl.html',
link: function(scope, element, attrs) {
}
}
});
You can use the angular select
directive together with ng-options
. 您可以将angular
select
指令与ng-options
一起使用。 This way you can provide arbitrary objects as values. 这样,您可以将任意对象作为值提供。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.