【问题标题】:Default value given in ng-model is not selected in drop downng-model 中给出的默认值未在下拉列表中选择
【发布时间】:2017-01-03 11:58:08
【问题描述】:

我正在我的应用中尝试简单的选择下拉菜单。我在 ng-model 中设置了默认值。但是在加载时,下拉菜单不会选择 ng-model 值。 以下是我的代码:

HTML:

View <select  ng-model="viewby" ng-change="setItemsPerPage(viewby)"><option>3</option><option>5</option><option>10</option><option>20</option><option>30</option><option>40</option><option>50</option></select> records at a time.

Js:

$scope.viewby=3             
  $scope.setItemsPerPage = function(num) {
    console.log( num);
  }

这里 ng-change 运行良好。 此处应在加载时选择“3”。我也尝试了 ng-init 和 selected='selected' ,但两者都不起作用。任何建议都会有所帮助。--谢谢

【问题讨论】:

    标签: angularjs html


    【解决方案1】:

    在 Angular 中,更好的方法是将选项定义为数组并绑定它们,以便更新 ng-model。

    JS:

     $scope.model = 30;
     $scope.options = [10, 20, 30,40,50];
    

    HTML

     <select  ng-change="setItemsPerPage(model)" ng-model="model" ng-options="value for value in options"></select>
    

    DEMO

    【讨论】:

      【解决方案2】:

      试试下面的 sn-p。这里默认选择的选项是20,您可以根据需要进行更改。

      var app = angular.module('app', []);
      app.controller("ctrl", function($scope) {
        $scope.selectedOption = 20;
        $scope.setItemsPerPage = function(num) {
          console.log(num);
        }
      });
      <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
      
      <div ng-app="app">
        <div ng-controller="ctrl">
      
          View
      
          <select ng-model="selectedOption" ng-change="setItemsPerPage(selectedOption)">
            <option>3</option>
            <option>5</option>
            <option>10</option>
            <option>20</option>
            <option>30</option>
            <option>40</option>
            <option>50</option>
          </select>
      
          records at a time.
      
        </div>
      
      </div>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-23
        • 2015-11-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多