选择2标签未使用Angularjs更改

时间:2019-06-26 04:12:06

标签: angularjs jquery-select2

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;

问题

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

enter image description here

3 个答案:

答案 0 :(得分:1)

当angularjs将Country的值与value<option>中的<option value="Country.CountryID">属性进行比较时,就会发生此问题。 Country是数字,而选项的值在string中。简而言之,问题在于类型不匹配。

documentation

  

当模型需要绑定到非字符串值时,您必须   使用指令明确将其转换(请参见下面的示例),或者   使用ngOptions指定选项集。这是因为一个选项   元素目前只能绑定到字符串值。

因此,您可以使用ngOptions解决此问题,如随附的代码段所示。

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

答案 1 :(得分:0)

使用ng-option代替ng-repeat ...的选项...

<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
    }

答案 2 :(得分:0)

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