处理Angular指令中的选择框更新

时间:2014-11-06 17:40:45

标签: angularjs angularjs-directive

uiModel.appreciation是一个键/值对象:

{ "key": "B", "value": "Better"}

在我的指示中:

scope.appreciationsArray = [{key: 'A', value: 'Good'}, {key: 'B', value: 'Better'}, {key: 'C', value: 'Best'}];

指令模板:

<select name="type" ng-change="onChangeAppreciationSelectBox($index)" class="form-control" ng-disabled="disabled" required ng-model="uiModel.appreciation.key" data-ng-options="appreciationObj.key as appreciationObj.value for appreciationObj in appreciationsList">
                </select>

这会呈现一个不错的选择框,并将所选项目设置为B / Better。 当更改为另一个项目时,我希望相应地更新uiModel.appreciation对象。到目前为止,只更新了密钥,值propertyallever保持其初始值。

在不使用自定义Javascript的情况下,必须能够找到正确的Angular方法吗?

1 个答案:

答案 0 :(得分:1)

使用欣赏作为模型和 comprehension expression 中的选择器而不是关键属性:

<select
    ng-model="uiModel.appreciation" 
    ng-options="appreciation.value for appreciation in appreciations">

&#13;
&#13;
angular.module('MyModule', [])

.controller('MyController', function($scope) {

  $scope.uiModel = {
    appreciation: {
      "key": "B",
      "value": "Better"
    }
  }

  $scope.appreciations = [{
    key: 'A',
    value: 'Good'
  }, {
    key: 'B',
    value: 'Better'
  }, {
    key: 'C',
    value: 'Best'
  }];

  $scope.uiModel = {
    appreciation: $scope.appreciations[0]
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>

<div ng-app='MyModule' ng-controller='MyController'>
<p>Selected appreciation: {{uiModel.appreciation | json}}</p>
<select
    ng-model="uiModel.appreciation" 
    ng-options="appreciation.value for appreciation in appreciations">
</select>
</div>
&#13;
&#13;
&#13;