AngularJs-SELECT中的ng模型 [英] AngularJs - ng-model in a SELECT

查看:81
本文介绍了AngularJs-SELECT中的ng模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JSfiddle

问题:

我的页面中有一个SELECT元素,其中用ng-repeat填充.它还有一个ng-model,它具有默认值.

I have a SELECT-element in my page, which is filled in with an ng-repeat. It also has a ng-model which has a default value.

当我更改值时,ng-model会适应,没关系.但是下拉列表在启动时显示了一个空插槽,应该在其中选择了具有默认值的项目.

When I change the value, the ng-model adapts, that's ok. But the dropdown-list shows an empty slot at launch, where it should have the item with the default value selected instead.

代码

<div ng-app ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

使用JS:

function myCtrl ($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

};

推荐答案

您可以使用 ng-selected 指令.它表达了如果诚实将设置选定的属性.

You can use the ng-selected directive on the option elements. It takes expression that if truthy will set the selected property.

在这种情况下:

<option ng-selected="data.unit == item.id" 
        ng-repeat="item in units" 
        ng-value="item.id">{{item.label}}</option>

演示

angular.module("app",[]).controller("myCtrl",function($scope) {
    $scope.units = [
        {'id': 10, 'label': 'test1'},
        {'id': 27, 'label': 'test2'},
        {'id': 39, 'label': 'test3'},
    ]

        $scope.data = {
        'id': 1,
        'unit': 27
        }

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
         <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

这篇关于AngularJs-SELECT中的ng模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆