我试图在选择控件中获取所有选定的项目,例如其值或标题。基本上,在用户从选择控件中选择了他/她想要的项目之后,我想获得所选项目的数量及其标题或值。
在我的html页面中,我有以下代码段:
<select ng-model="selectedValues" multiple>
<option >All Booth</option>
<option> Washroom</option>
</select>
<button ng-click="apply()" type="button">Apply</button>
在我的控制器中,我有以下代码段:
$scope.apply = function () {
// Get the number of selected items and its title or value
}
有谁知道我能做到这一点的方法?感谢。
答案 0 :(得分:1)
请查看演示:
angular.module('app', [])
.controller('appCtrl', function ($scope) {
$scope.apply = function () {
if ($scope.selectedValues != undefined && $scope.selectedValues.length > 0) {
// Get the number of selected items and its title or value
var selectedTitles = $scope.selectedValues;//Get title or value
var noSelectedItems = $scope.selectedValues.length;//Get the number of selected items
console.log("Total items selected :" + noSelectedItems + " titles '" + selectedTitles.toString() + "'");
}
else {
console.log("No item selected");
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.js"></script>
</head>
<body ng-app="app" ng-controller="appCtrl">
<select ng-model="selectedValues" multiple>
<option>All Booth</option>
<option>Washroom</option>
</select>
<button ng-click="apply()" type="button">Apply</button>
</body>
</html>
答案 1 :(得分:0)
如果在select
而不是angularjs
处理ng-repeat
元素,请使用ngOptions属性。有关更多信息,请单击here以获取ngOptions文档。
工作演示:
var myApp = angular.module('myApp', []);
myApp.controller('MyCtrl',function($scope) {
$scope.items = [
{
title: 'All Booth',
value: 'All Booth'
},
{
title: 'Washroom',
value: 'Washroom'
}
];
$scope.apply = function(selectedValues) {
var selectedValuesLength = selectedValues.length;
console.log(selectedValuesLength); // selected items count
for(var i in selectedValues) {
console.log(selectedValues[i]); // selected items title
}
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
<select multiple="true" ng-model="selectedValues" ng-options="item.value as item.title for item in items">
</select>
<button ng-click="apply(selectedValues)" type="button">Apply</button>
</div>
&#13;