来自资源默认值的AngularJS和ng-options

时间:2013-08-06 11:45:56

标签: angularjs

目前,我通过在angularjs中设置ng-options的默认值来实现目标。 有人可以帮帮我吗?

我从资源中获取选项。

<select id="customer_country" ng-model="customer.country" ng-options="country.name for country in countries" style="width:230px;">
</select>

我目前的解决方法是设置默认值:

 $scope.countries = Country.query(function() {
    $scope.customer.country = $scope.countries[0];
 });

但我不认为这是最好的方法。 我搜索了互联网,但没有找到一个好的答案。 您将如何分配默认值?

目前我需要它,它没有空值。有时它也不会有空值,也不应该使用模型中的值来更新模型。

4 个答案:

答案 0 :(得分:6)

我自己遇到了同样的问题,我相信这是最好的解决方法。这也是他们在documentation for the ng-options directive中完成的方式。

答案 1 :(得分:1)

以下是我一直在使用的代码示例。

HTML

<select ng-model="agent.id" ng-options="user.id as user.username for user in users"></select>

控制器

$scope.agent = {
    id: 2,
    address:4
};

它将下拉列值设置为2,使用代理ID映射到每个下拉元素的user.id.不知道这是否有帮助。

答案 2 :(得分:0)

$scope.customer = {country: $scope.countries[0]};

$scope.customer.country = $scope.countries[0];

答案 3 :(得分:0)

我注意到如果其中一个选项的值等于模型,则angular会将其指定为默认选定值。

以下是一个示例coffeescript代码(请注意,此处currentPlant.status的值为'expired'):

控制器:

$scope.statusArr = [
  {value: 'active', display: 'Active'},
  {value: 'expired', display: 'Expired'}
]

$scope.currentPlant = CurrentPlants.get id : $routeParams.id

HTML:

<select class="form-control" ng-model="currentPlant.status" ng-options="status.value as status.display for status in statusArr">
        </select>

在此示例中,angular将'expired'指定为默认选定选项。