angularjs - 选择ng模型索引

时间:2017-01-03 07:25:48

标签: javascript angularjs angularjs-scope

我试图在选择控件中获取所有选定的项目,例如其值或标题。基本上,在用户从选择控件中选择了他/她想要的项目之后,我想获得所选项目的数量及其标题或值。

在我的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


}

有谁知道我能做到这一点的方法?感谢。

2 个答案:

答案 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文档。

工作演示:

&#13;
&#13;
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;
&#13;
&#13;