AngularJS ngOptions select 默认选项

AngularJS ngOptions select default option

我有以下 select 元素,它是使用 angular 的 ngOptions 指令动态填充的。

<select ng-options="group.parameterGroupId as group.name for group in parameterGroups" 
        ng-change="getParameterGroup(group.parameterGroupId)" 
        ng-model="group.parameterGroupId">
    <option value="">== Choose Group ==</option>
</select>

如何在 select 编辑下拉列表中的另一个值后,以编程方式 select 默认 == Choose Group == 选项?

我尝试在我的控制器中将 $scope.group.parameterGroupId 设置为 null"",但都没有按预期工作。在这两种情况下,当前 selected 的选项将保持 selected。

使用 AngularJS v1.4.3.

好吧,您可以将某些模型归因于您的默认选项。看一看:

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.options = [
        { desc: 'op1' },
        { desc: 'op2' },
        { desc: 'op3' }
    ]
    $scope.reset = function(){
     $scope.selected = $scope.default;
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <select ng-options="op as op.desc for op in options" ng-model="selected">
    <option value="" ng-model="default">== Choose Group ==</option>
  </select>
    {{selected}}
    
    <br />
    <button ng-click="reset()">Reset!</button>
</div>

这应该可以解决问题。

我的问题是我的 <select> 使用 ngInclude 指令包含在我的页面中。我发现 ngInclude 指令实际上为包含的模板创建了一个子范围。因此,为了能够设置 selected 组,我需要使我的 select 的 ng-model 可以从其父范围访问。

我最终也采用了@Italo Ayres 的解决方案,以访问我的 select 的默认值。这是我更正的标记,它使用 $parent 访问我的模板的父范围,我的 <select> 包含在其中。

<select ng-options="group.parameterGroupId as group.name for group in parameterGroups" 
        ng-change="getParameterGroup(group.parameterGroupId)" 
        ng-model="$parent.group.parameterGroupId">
    <option value="" ng-model="$parent.defaultGroup">== Choose Group ==</option>
</select>

然后在我的控制器中,我像这样将 selected 组设置为默认值。

$scope.group {
    parameterGroupId: $scope.defaultGroup
};

注意,我没有使用$scope.group.parameterGroupId = $scope.defaultGroup,因为$scope.group可能到这个语句的时候还没有定义