【问题标题】:Set default value for dropdownlist using angularjs?使用angularjs为下拉列表设置默认值?
【发布时间】:2013-11-23 21:09:00
【问题描述】:

我有填充下拉列表的代码和获取列表中最后一项的 javascript 变量。现在我要做的就是选择最后一项作为默认值。我错过了什么?

<div class="row">
<div>
    <select ng-init="lastItem" ng-model="congressFilter" ng-options="cc.congressLongName for cc in ccList"></select>
</div>
<div class="grid-style" data-ng-grid="userGrid">
</div>

   ccResource.query(function (data) {
    $scope.ccList.length = 0;
    angular.forEach(data, function (ccData) {
        $scope.ccList.push(ccData);
    })

    //Set default value for dropdownlist?
    $scope.lastItem = $scope.ccList[$scope.ccList.length - 1];
});

【问题讨论】:

  • 不应该是ng-model="lastItem"吗?

标签: javascript asp.net angularjs


【解决方案1】:

您只需在控制器中为 congressFilter 分配一个值。

 $scope.congressFilter = 'someVal';

不过,这在一定程度上取决于您的数据的外观。

【讨论】:

    【解决方案2】:

    这可能对新开发人员有所帮助。需要在选项中添加默认 id 以显示默认项。

    下面的代码示例我们在控制器 $scope 中添加 [ $scope.country.stateid = "4" ] 来设置默认值。

        var aap = angular.module("myApp", []);
    
        aap.controller("MyContl", function($scope) {
          $scope.country = {};
          $scope.country.stateid = "4";
    
          $scope.country.states = [{
            id: "1",
            name: "UP"
          }, {
            id: "4",
            name: "Delhi"
          }];
        });
    
    <body ng-app="myApp">
      <div ng-controller="MyContl">
        <div>
          <select ng-model="country.stateid" ng-options="st.id as st.name for st in country.states">
          </select>
         ID :  {{country.stateid}}
        </div>
      </div>
    </body>
    

    【讨论】:

      猜你喜欢
      • 2016-04-10
      • 1970-01-01
      • 2016-11-16
      • 2017-04-28
      • 2020-07-06
      • 2013-10-23
      • 2016-04-19
      • 2011-06-14
      • 1970-01-01
      相关资源
      最近更新 更多