【问题标题】:How to get selected item value如何获取所选项目的价值
【发布时间】:2016-08-17 07:25:30
【问题描述】:

我在我的 HTML 页面中创建列表:

 <label class="item item-input">
 <span class="input-label">Select date</span>
 <select  ng-model="search.dateOption" ng-options="opt as opt.label for opt in options">
 </select>
 </label>

在我的控制器中,我定义了选项:

$scope.options = [
  { label: 'Today'},
  { label: 'This week'},
  {  label: 'This month'},
  { label:'Other'}
]

我使用以下函数来获取所选项目:

 $scope.selectedDate = function(){
 $scope.search={}
 console.log($scope.search )
 }

我在控制台中收到undefined

【问题讨论】:

    标签: angularjs selecteditem


    【解决方案1】:

    最好为下拉列表对象设置一个 id

    var editer = angular.module('editer', []);
    
    function myCtrl($scope) {
    
      $scope.dateOption = null;
      $scope.options = [{
        id: 1,
        label: 'Today'
      }, {
        id: 2,
        label: 'This week'
      }, {
        id: 3,
        label: 'This month'
      }, {
        id: 4,
        label: 'Other'
      }];
    
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="editer" ng-controller="myCtrl" class="container">
    
      <label class="item item-input">
        <span class="input-label">Select date</span>
        <select ng-model="dateOption" ng-options="opt as opt.label for opt in options">
        </select>
      </label>
    
      <pre>{{dateOption}}</pre>
    </div>

    【讨论】:

    • 感谢您的回复。但是我如何从我的控制器中获取 dateOption 的值?
    • 你可以设置 $scope.dateOption = null;
    【解决方案2】:

    像这样试试。

    var editer = angular.module('editer', []);
    function myCtrl($scope) {
    
      $scope.options = [
      { label: 'Today'},
      { label: 'This week'},
      {  label: 'This month'},
      { label:'Other'}
    ];
      
      $scope.selectedDate = function(){
         console.log($scope.search )
     }
    }
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
    <div ng-app="editer" ng-controller="myCtrl" class="container">
    
    <label class="item item-input">
     <span class="input-label">Select date</span>
     <select  ng-model="search.dateOption" ng-options="opt as opt.label for opt in options" ng-change="selectedDate()">
     </select>
     </label>
      
      <pre>{{search | json}}</pre>
    </div>

    【讨论】:

    • 感谢您的回复。它在这里工作,但在我的项目中不起作用。可能是因为我的 angularjs 版本。我正在使用 1.5.5
    • 没有。控制台显示什么??
    • 没有任何东西显示在控制台中只是 undefined 。但是&lt;pre&gt;{{search | json}}&lt;/pre&gt; 运行良好。
    • 请仔细检查您的代码。一切都是正确的。
    • 是的,我检查得很好。我复制并粘贴您的代码,但在控制台中未定义:\\
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-23
    • 1970-01-01
    • 2018-02-03
    • 1970-01-01
    相关资源
    最近更新 更多