首页 > 解决方案 > 角度模式形式的数组长度

问题描述

我有这个架构:

    {
     "type": "object",
     "title": "Comment",
     "required": [
     "comments"
      ],
  "properties": {
    "comments": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "name": {
            "title": "Name",
            "type": "string"
          },
          "email": {
            "title": "Email",
            "type": "string",
            "pattern": "^\\S+@\\S+$",
            "description": "Email will be used for evil."
          },
          "spam": {
            "title": "Spam",
            "type": "boolean",
            "default": true
          },
          "comment": {
            "title": "Comment",
            "type": "string",
            "maxLength": 20,
            "validationMessage": "Don't be greedy!"
          }
        },
        "required": [
          "name",
          "comment"
        ]
      }
    }
  }
}

这是一组评论。我可以添加和删除评论。

默认情况下,如何始终渲染数组的 2 项?

我已经尝试过maxItemsminItems但这些参数不会呈现项目。

标签: javascriptangularjsangular-schema-form

解决方案


目前有两种方法可以做到这一点。

首先是将它们设置在默认模型中,使其看起来像:

$scope.model = {
    "comments": [{},{}]
}

第二个是在数组上使用 onChange:

"onChange": function(val) { if(val.length < 2) val.push({}); }

两者之间的区别在于 onChange 不允许它低于您设置的最小长度,而第一个选项仅用于初始默认值。


推荐阅读