【问题标题】:Select 2 Label is not changed using Angularjs选择 2 标签未使用 Angularjs 更改
【发布时间】:2019-06-26 04:12:06
【问题描述】:

HTML

<select ng-model="Country" id="Country" class="select2" ng-change="viewState()">
    <option value=''>Select Country</option>
    <option ng-repeat="Country in AllCountry"
            ng-value="[[Country.CountryID]]"
            value="[[Country.CountryID]]">[[Country.CountryName]]
    </option>
</select>

Angulajs

$scope.Country=23;

问题

当我运行此代码时,选择了值但标签未更改,我附上了屏幕截图。

【问题讨论】:

标签: angularjs jquery-select2


【解决方案1】:

当 angularjs 将您的 Country 值与 &lt;option&gt; 内的 value 属性进行比较时会出现问题@ e-e &lt;option value="Country.CountryID"&gt;Country 是数字,而选项的值在 string 中。简而言之,问题在于类型不匹配。

documentation 这么说

当模型需要绑定非字符串值时,必须 使用指令显式转换它(参见下面的示例)或 使用 ngOptions 指定选项集。这是因为一个选项 element目前只能绑定字符串值。

所以你可以使用ngOptions来解决这个问题,你可以在附加的代码sn-p中看到。

<select name="mySelect" id="mySelect"
  ng-options="option.CountryID as option.CountryName for option in AllCountry" ng-model="Country">
</select>

【讨论】:

  • 我试过了,但它不起作用。 (它在正常选择上完美工作,在 select2 上不起作用)
【解决方案2】:

使用 ng-option 代替带有 ng-repeat 的 option ...

<select ng-model="Country" id="Country" class="select2" ng-change="viewState()">
    <option value=''>Select Country</option>
    <option ng-repeat="Country in AllCountry"
            ng-value="Country.CountryID"
            value="{{Country.CountryID}}">{{Country.CountryName}}
    </option>
</select>

请使用 angular{{}} 而不是 [[]] 进行绑定....希望它对您有用

$scope.Country=22;
    $scope.AllCountry = {
    "India": {
        "CountryName":"India",
        "CountryID": 1
    },
    "USA": {
        "CountryName":"USA",
        "CountryID": 22
    },
    "USR": {
    "CountryName":"USR",
        "CountryID": 2
    }

【讨论】:

  • 我使用 laravel + angularjs 这就是为什么我使用 [[]]
  • 好的,Laravel 是一个框架,但是无论你在哪里替换视图中的角度值,它都必须在尖括号内。
  • 我们可以在 Angular js 中使用自定义 interpolateProvider
【解决方案3】:

HTML

<ui-select ng-model="CountryScope.selected" theme="bootstrap">
    <ui-select-match placeholder="Select or search a person in the list...">[[$select.selected.CountryName]]</ui-select-match>
    <ui-select-choices  repeat="Country in (AllCountry | filter: $select.search) track by Country.CountryID">
       <div ng-bind-html="Country.CountryName | highlight: $select.search"></div>
       <small ng-bind-html="Country.CountryName | highlight: $select.search"></small>
    </ui-select-choices>
</ui-select>

AngularJS

$scope.AllCountry=[
        {  CountryID: 1, CountryName: 'United States' },
        {  CountryID: 2,  CountryName: 'Argentina' },
        {  CountryID: 3,   CountryName: 'Argentina' }
      ];

设置值

$scope.CountryScope.selected= { CountryID: 2,  CountryName: 'Argentina' };

获取价值

$scope.CountryScope.selected.CountryID

点击这里查看DEMO

点击Reference

【讨论】: