如何更改控制器中选择输入的选定值?

时间:2014-03-29 23:16:21

标签: angularjs

我的模板:

<select ng-model="state" ng-options="state.name for state in states">
    <option value="">ALL</option>
</select>

我的控制器:

var stateList = [
  { name: 'ALABAMA', abbreviation: 'AL'},
  { name: 'ALASKA', abbreviation: 'AK'},
  { name: 'ARIZONA', abbreviation: 'AZ'},
  { name: 'ARKANSAS', abbreviation: 'AR'},
  ...
]

$scope.states = stateList;
$scope.state = 'ALL';  // Default

$scope.updateStateModel = function(state) {
  $scope.state = state.toUpperCase();  // Does nothing
};

$scope.state的值确实发生了变化,但没有反映在<select>输入上。如何正确绑定它以使<select>的值与$scope.state同步?

1 个答案:

答案 0 :(得分:1)

ngModel 需要绑定到同一个对象类型,这是一个有效的例子:

<强> HTML:

<div ng-app="App"  ng-controller="ctrl">
<select ng-model="state" ng-options="state.name for state in states">
    <option value="">ALL</option>
</select>
    <div ng-repeat="state in states"><span ng-click="updateStateModel(state)">{{state.name}}</span></div>
</div>

<强> JS:

function ctrl($scope) {
        $scope.states = [{name:"aa"},{name:"bb"},{name:"cc"}];
    $scope.state = 'ALL';  // Default

    $scope.updateStateModel = function(state) {
      $scope.state = state; 
    };
 }

实例:http://jsfiddle.net/choroshin/3RGpv/