简体   繁体   English

AngularJS - 指令的 templateUrl 中的表单验证

[英]AngularJS - Form Validation in a templateUrl of a directive

I am trying to use angular's form validation from inside a templateUrl.我正在尝试从 templateUrl 内部使用 angular 的表单验证。

I have a directive that loads a templateUrl in which i have a form with inputs that get ng-required and ng-regex values from directive scope.我有一个加载 templateUrl 的指令,其中我有一个表单,其中包含从指令范围获取 ng-required 和 ng-regex 值的输入。 Now, i tried to put in my directive's scope form: '=', but when i access scope.form it is undefined.现在,我尝试输入指令的范围形式:'=',但是当我访问 scope.form 时它是未定义的。

I must specify that my submit button is outside of the form, and when clicked ng-click='save($index)' it must first check that the form is valid and then proceed with saving the edited data.我必须指定我的提交按钮在表单之外,当单击 ng-click='save($index)' 时,它必须首先检查表单是否有效,然后继续保存编辑过的数据。 scope.save() is defined in my directive. scope.save() 在我的指令中定义。

this is from template:这是来自模板:

 <tr data-ng-repeat="row in source.data "  data-ng-class="{'selected':row.$_selected}" >
            <td data-ng-repeat="c in settings.columns" data-ng-click="toggleSelect(row)" >         
                <form name="editForm" id="editForm" novalidate> 
                    <div ng-switch on="c.type" ng-show="editMode[$parent.$index]">
                        <span ng-switch-when="text" >
                            <input type="{{c.type}}"  data-ng-model="row[c.name]" ng-required="{{c.isRequired}}" ng-pattern="{{c.regex}}"/>
                        </span>
                        <span ng-switch-when="select" >
                            <select  data-ng-model="row[c.name]" ng-selected="row[c.name]" ng-init="row[c.name]" ng-options="item.value as item.name for  item in c.items" ng-required="{{c.isRequired}}">
                                <!--<option data-ng-repeat="(value, name) in c.items" value="{{value}}">{{name}}</option>-->
                            </select>
                        </span>
                        <span ng-switch-when="textarea">
                            <textarea  ng-model="row[c.name]" ng-required="{{c.isRequired}}" ng-pattern="{{c.regex}}">                                                      
                            </textarea>
                        </span>
                        <span ng-switch-when="checkbox">
                            <!--<label for="checkboxInput">{{c.name}}</label>-->
                            <input name="checkboxInput" type="checkbox" data-ng-model="row[c.name]" ng-true-value="{{c.true}}" ng-false-value="{{c.false}}"/>
                        </span>
                        <span ng-switch-default="">
                            {{row[c.name]}}
                        </span>                     
                    </div>          
                </form>         
                <span ng-hide='editMode[$parent.$index]'>{{row[c.name]}}</span>
            </td>                  
            <td>
                <a href="{{row[settings.specialFields.url]}}" class="btn btn-default opacity75" data-ng-if="row[settings.specialFields.url]">
                    <span class="glyphicon glyphicon-chevron-right"></span>
                </a>                                      
            </td>                
            <td data-ng-if="row[settings.specialFields.isEditable]">
                <button ng-click="edit(row)" ng-show="!editMode[$index]" class="btn btn-primary" >
                    edit {{$index}}
                </button>                   
                <button ng-click="save($index)" ng-disabled=""  ng-show="editMode[$index]" class="btn btn-primary">
                    save
                </button>
                <button ng-click="cancel($index)" ng-show="editMode[$index]"  class="btn btn-default">
                    cancel
                </button>                     
            </td> 
        </tr>

and this is from my directive:这是来自我的指令:

scope: {
        settings: '=',
        source: '=',
        form: '='

    },

    templateUrl: function (element, attr) {
        return attr.templateUrl || 'src/grid.html';
    },
    link: function (scope, element, attrs) {

        scope.editMode = [];     

        scope.editing = false;
        scope.previousData = {};

        scope.edit = function(field) { 

            scope.editing = scope.source.data.indexOf(field);               
            scope.editMode[scope.editing] = true;               
            scope.previousData = angular.copy(field);

        };

        scope.save = function(index){
            console.log(scope.form);
            scope.editMode[index] = false;              

            if (scope.editing !== false ) {     
                //do the saving            
                scope.editing = false;
            } 
        };



        scope.cancel = function(index){
            scope.editMode[index] = false;

            if (scope.editing !== false) {
                scope.source.data[scope.editing] = scope.previousData;
                scope.editing = false;
            }
        }

Here you go:干得好:

Working Form工作表

  • Form button is outside of form, and could also be outside of directive.表单按钮在表单之外,也可能在指令之外。 It doesn't matter with Angularjs.这与 Angularjs 无关。

  • There are two inputs, both have required and both have regex validation as you stated.正如您所说,有两个输入,两者都需要,并且都具有正则表达式验证。

  • There is a directive with a templateURL有一个带有 templateURL 的指令

The important thing to remember here is that the form must have a name, and then it is referenced by that name as in: scope.myForm when这里要记住的重要一点是表单必须有一个名称,然后通过该名称引用它,如:scope.myForm when

You don't have to name the input fields as I did in the plunker, but if you do, and they are ALL different values from one another, then you can do this: scope.myForm.myInputName.$valid to see if each input is valid if you wished.您不必像我在 plunker 中所做的那样命名输入字段,但是如果您这样做了,并且它们的值彼此不同,那么您可以这样做:scope.myForm.myInputName.$valid 以查看每个如果您愿意,输入是有效的。

But, the actual form will not be valid until ALL the inputs are valid, so you probably just need to call valid on the form itself as in in the provided example.但是,在所有输入都有效之前,实际表单将无效,因此您可能只需要像提供的示例中那样在表单本身上调用 valid 。

If you move the button outside of the directive, you will have to move the submit function from the directive to the controller (most likely).如果将按钮移到指令之外,则必须将提交功能从指令移动到控制器(很可能)。

Let me know if this helps, I can change things if needed.如果这有帮助,请告诉我,如果需要,我可以更改内容。 Also, try the plunker first with your question, then post what's going on with that new code;另外,先用你的问题试试plunker,然后发布新代码的情况; just fork the plunker and provide a link.只需 fork plunker 并提供链接。

Here is the plunker code just in case...这是plunker代码以防万一......

<!DOCTYPE html>
  <html>

  <head>
    <link data-require="bootstrap@*" data-semver="3.2.0" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.css" />
    <script data-require="jquery@*" data-semver="2.1.1" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script data-require="bootstrap@*" data-semver="3.2.0" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.js"></script>
    <script data-require="angular.js@1.3.7" data-semver="1.3.7" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.7/angular.js"></script>
    <script data-require="angular-ui-bootstrap@0.12.0" data-semver="0.12.0" src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.12.0.min.js"></script>
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
  </head>

  <div ng-app="myApp">
    <div ng-controller="MyCtrl">
      <my-directive></my-directive>
    </div>
  </div>
</html>

<form name="myForm" novalidate>
  <label>Input #1 (required)</label><br>
  <input ng-model="form.data.myName" name='myName' ng-pattern="/\D+/" ng-required="true" /> <span ng-show="myForm.myName.$error.pattern">Takes anything but digits</span><br>
  <br>
  <label>Input #2 (required)</label><br>
  <input ng-model="form.data.myEmail" name='myEmail' ng-pattern="/\d+/" ng-required="true" /> <span ng-show="myForm.myEmail.$error.pattern">Takes only digits</span>
</form>
<br>
<p># I'm a button that is outside of the form!</p>
<p ng-model="form.submitted">Form Submitted: <span class="blue">{{ form.submitted }}</span></p>
<p>Form Valid?: <span class="blue">{{ myForm.$valid }}</span></p>
<button ng-click="submitForm('myForm')">Submit Form</button>

<p ng-model="form.data">Here is the Form data:</p>
{{ form.data }}


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

app.controller('MyCtrl', function ($scope) {});

  app.directive("myDirective", function () {

    return {
      restrict: 'AE',
      require: '?ngModel',
      templateUrl: 'my-directive.html',

      link: function (scope, elm, attrs, ctrl) {
      scope.form = {submitted: false, data: {}};

      scope.submitForm = function(formname){
        console.log(scope[formname].myEmail)
        console.log(scope.formname)
        console.log(scope[formname].$valid)
        scope.form.submitted = true;
      }
    } // end link
  } // end return
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM