【问题标题】:HTML AngularJS - select bindingHTML AngularJS - 选择绑定
【发布时间】:2015-03-19 19:10:29
【问题描述】:

我有一个表格,当你选择一个名字时会自动填写。

<select ng-model="selected" ng-options="user as user.name for user in users" >
</select>

所以当我选择我的用户时,下一个字段(地址、电子邮件、电话...)将填充所选用户的数据。

<input type="text" id="address" value="{{selected.address}}">

我的问题是我有一个包含所有国家/地区的选择,我想获得所选国家/地区的显示。

<select class="form-control">
            <option value="AF">Afghanistan</option>
            <option value="AX">Aland Islands</option>
            <option value="AL">Albania</option>.....

因此,当我选择居住在美国的“Marc”时,我希望选择的国家/地区显示“美国”而不是第一个选项“阿富汗”。

希望我的问题足够清楚。

谢谢!

【问题讨论】:

  • 在国家/地区选择上使用 ng-options 和 ng-model 也像 ng-model="user.country_code" ng-options="c.code as c.name for c in countries"

标签: html angularjs


【解决方案1】:

您可以使用ng-selected 指令。

假设您选择的人有一个 country 属性,其中包含国家代码,并且您有一个国家对象数组 {code: 'AF', name: 'Afganistan'}

<select ng-model="selected.country" >
    <option ng-repeat="country in countries" 
            value="{{country.code}}" 
            ng-selected="country == selected.country">
        {{country.name}}
    </option>
</select>

【讨论】:

    【解决方案2】:

    DEMO

     <select ng-model="selected" ng-options="user as user.name for user in users" >
    </select>
    
      <select class="form-control" ng-model="selected.country">
                <option value="AF">Afghanistan</option>
                <option value="AX">Aland Islands</option>
                <option value="AL">Albania</option>
    
      </select>
    

    在您的控制器中:

    angular.module("SO29142872", [])
      .controller("MainCtrl", function($scope) {
    
      $scope.users = [{
          "name" : "Mohamed RIas",
          "country" : "AX"
        },{
          "name" : "Weedoze",
          "country" : "AL"
        }]
    
    });
    

    【讨论】: