从控制器设置表单错误

时间:2017-09-11 11:13:39

标签: javascript angularjs

我的表格:

  <form name="projectForm">
    <div>
          <md-checkbox ng-repeat="item in $ctrl.items"
             ng-model="item.selected"
             ng-change="$ctrl.itemsChanged()"
             aria-label="Checkbox 1" class="md-primary">
            {{item.title}}
        </md-checkbox>
    </div>
  </form>

我的组件:

var BuyWizardCtrl = (function () {
    function BuyWizardCtrl() {

        this.items = [
            {
                title: 'Item 1',
                selected: false
            },
            {
                title: 'Item 1',
                selected: false
            }
        ];

    }
    BuyWizardCtrl.prototype.itemsChanged = function () {
        this.selectedItems = this.items.filter((o)=>{
          return i.selected === true;
        });
        if(this.selectedItems.length === 0){
          // Set form error here
        }
    };

    return BuyWizardCtrl;
}());

我有复选框的表单。必须至少检查其中一个复选框才能使表单有效。是否可以从组件控制器设置表单错误?

1 个答案:

答案 0 :(得分:1)

首先将名称和required属性设为复选框:

  <form name="projectForm">
    <div>
          <md-checkbox ng-repeat="item in $ctrl.items"
             ng-model="item.selected"
             ng-change="$ctrl.itemsChanged()"
             required="true"
             name="checkbox"
             aria-label="Checkbox 1" class="md-primary">
            {{item.title}}
        </md-checkbox>
    </div>
  </form>

在控制器中:

 $scope.projectForm.$setDirty() = true // to set form dirty

 $scope.projectForm.checkbox.$error.required = true;//I guess You need this