验证ng-repeat中的表单

时间:2014-04-17 10:48:08

标签: javascript json forms angularjs ng-repeat

所以我有一个用于输入信息的动态表单构建器。我现在的问题是,我希望根据我可以在构建表单的JSON中添加的键或属性为输入元素添加必需项。

之前有没有人这样做过,因为我无法想到一个好的解决方法。

这是JSON和表单构建器指令。

表单构建器JSON

{
  "book": {
    "config":{
      "citations": true,
      "order": ["title", "author", "publisher", "issued", "publisher-place", "edition"]
    },
    "fields": {
      "title": {
        "label": "Title",
        "placeholder": "Enter Title",
        "type": "string"
      },
      "author": {
        "label": "Author",
        "placeholder": "Enter Author",
        "type": "string"
      },
      "publisher": {
        "label": "Publisher",
        "placeholder": "Enter Publisher",
        "type": "string"
      },
      "issued": {
        "label": "Year of Publication (YYYY-MM-DD)",
        "placeholder": "Enter year of publication (YYYY-MM-DD)",
        "type": "string"
      },
      "publisher-place": {
        "label": "Place of Publication",
        "placeholder": "Enter Place of Publication",
        "type": "string"
      },
      "edition": {
        "label": "Edition",
        "placeholder": "Enter edition",
        "type": "string"
      }
    }
  },
  "chapter": {},
  "article": {},
  "website": {}
}

表单生成器指令

angular.module('ReferenceME.directives.formBuilder', [
  'templates',
  'ngResource'
  ])

.directive('formBuilder', ['$resource', '$http', function ($resource, $http) {
  var sortFormData = function (data) {
    console.log(data);
    for (var item in data) {
      for (var field in data[item].fields) {
        data[item].fields[field].model = field;
      }
    }

    return data;
  };

  return {
    templateUrl: 'formBuilder/formBuilder.html',
    link: function (scope, element, attrs) {
      $http.get('assets/templates/forms.json').then(function (response) {
        scope.formFields = sortFormData(response.data);

        scope.referenceForm.fields = {type:scope.manualEntryType};
      });
    }
  }
}]);

表单构建器模板

<form ng-submit="createReference(referenceForm)" class="manual-entry__form animate__labels-left" name="referenceForm" novalidate>
  <p class="manual-entry__field" ng-repeat="field in formFields[manualEntryType].fields">
    <input type="text" ng-model="referenceForm.fields[field.model]" placeholder="{{field.placeholder}}" />
    <label>{{field.label}}</label>
  </p>
  <input class="submit__button" type="submit" value="ReferenceME">
</form>

1 个答案:

答案 0 :(得分:1)

在这种情况下,不能使用ng-required属性吗?引用here

<input class="submit__button" type="submit" value="ReferenceME" ng-required="{{field.required}}">