Angular正式 - 复选框模型值模板



我有一个小表单,例如某些复选框的默认值,例如,当单击" dog"的复选框" dog"时,单击了单击的形式时,它将添加到构成人模型一部分的狗串的"宠物"阵列。我该如何正式实现?

{
     key: "dog",
     type: "checkbox",
     templateOptions: {
          ???
     }
}

表格示例:

Person name: Joe
Pets:
[x] dog

这将把模型设置为:

 {
      "name": "Joe"
      "pets": [ "dog" ]
 }

@veg,这个问题是针对角度的,而不是角度的。这不一样。显着。

在您的初始化中:

vm.model = { //initialize a model with a pets property holding an empty array.
  pets: []
}

在您的字段模型中:

{
   key: 'dog',
   type: 'checkbox',
   templateOptions: {
      label: 'dog',
      onChange: function($viewValue, $modelValue, $scope) {
        if($modelValue) $scope.model.pets.push('dog'); //if it's true--add it
        else { //need to remove it from the array
           var index = $scope.model.pets.indexOf('dog'); //get the index
           $scope.model.pets.slice(index, index+1); //remove it from the array
        }
      }
   },
}

最新更新