将ng-model应用于多个选择的组

时间:2016-04-25 22:19:30

标签: angularjs angular-ngmodel

对于多选组,我可以通过这个简单的例子构建UI:

<div ng-controller="MyCtrl">
<!-- choose colour and size -->
<fieldset ng-repeat="(fieldName, field) in fields">
<label ng-repeat="choice in field">
  <input ng-model="field" type="radio" />
    {{choice}}
</label>
</fieldset>
choices: {{fields}}

及其javascript:

var myApp = angular.module('myApp',[]);

function MyCtrl($scope) {
  $scope.fields = { /* in practice, the number of fields is dynamic */
  field1: ["red", "blue", "black"], 
  field2: ["big", "small", "medium"]
  }
}

生成的用户界面允许用户做出选择,但{{fields}} ng-model似乎并不存在,因为当用户做出选择时,其价值不会发生变化。

我认为也许我需要一个不同的ng-model变量,例如

$scope.choices = {field1: "", field2: ""}

$scope.fields一起使用以保留用户的选择。但各种尝试使用新变量失败了。我确信这样做的正确方法在这里受到质疑和回答。请耐心等待我的搜索。

1 个答案:

答案 0 :(得分:1)

首先,您的单选按钮没有值,因此您无法绑定任何内容。添加value="{{choice}}"

其次,您正在尝试绑定到field,在这种情况下,这是一个像["red", "blue", "black"]这样的值数组,这些数值没有意义。你需要绑定其他东西。

您应该将您的数据结构更改为类似下面的内容,其中包含我们可以为单选按钮迭代的数组,以及我们将使用ng-model绑定到的属性。

&#13;
&#13;
var myApp = angular.module('myApp', []);

myApp.controller("MyCtrl", MyCtrl);

function MyCtrl($scope) {

  $scope.fields = { /* in practice, the number of fields is dynamic */
    field1: {
      choices: ["red", "blue", "black"],
      selected: "red"
    },
    field2: {
      choices: ["big", "small", "medium"],
      selected: "big"
    }
  }

}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js"></script>
<div ng-app="myApp" ng-controller="MyCtrl">
  <!-- choose colour and size -->
  <fieldset ng-repeat="(fieldName, field) in fields">
    <label ng-repeat="choice in field.choices">
      <input ng-model="field.selected" type="radio" value="{{choice}}" />{{choice}}
    </label>
  </fieldset>
  <br/>Fields: {{fields}}
</div>
&#13;
&#13;
&#13;

相关问题