2014-02-28 34 views
87

Angular是否有可能以類似的方式驗證單個分離的<input>?我在想這樣的事情:AngularJS <input>驗證沒有包含<form>

<div class="form-group"> 
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5"> 
    <span class="error" ng-show="myInput.$error.maxlength">Too long!</span> 
</div> 

上面的例子不起作用。將其包含在<form>中,並用ng-show="myForm.myInput.$error.maxlength"替代ng-show有所幫助。

是否可以在不使用<form>的情況下執行此操作?

+2

你試過了嗎?我不認爲這是事實,我相信Angular在幕後創建了一個'form.FormController',用於跟蹤表單的輸入狀態,如'valid \ invalid&dirty \ pristine.'。 .angularjs.org/api/ng/type/form.FormController –

回答

160

您可以使用ng-form角度指令(see docs here)對任何內容進行分組,即使在html表單之外。然後,你可以利用角度FormController。

<div class="form-group" ng-form name="myForm"> 
    <input name="myInput" type="text" class="form-control" ng-model="bindTo" ng-maxlength="5"> 
    <span class="error" ng-show="myForm.myInput.$error.maxlength">Too long!</span> 
</div> 

Example

+0

按照plunker中的示例:http://plnkr.co/edit/QJ7Qps?p=preview –

+0

接受此答案。這就是我一直在尋找,雖然答案來得太遲了:) – Wojtek

+0

這也幫助我了。我把頭髮拉出來,偶然發現了這一點。謝謝! –

-1
<!DOCTYPE html> 
<html ng-app="plunker"> 
<head> 
    <meta charset="utf-8" /> 
    <title>AngularJS Plunker</title> 
    <script>document.write('<base href="' + document.location + '" />');</script> 
    <link rel="stylesheet" href="style.css" /> 
    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.5/angular.min.js"> </script> 

</head> 

<body ng-controller="MainCtrl"> 
    <div class="help-block error" ng-show="test.field.$error.required">Required</div> 
    <div class="help-block error" ng-show="test.firstName.$error.required">Name Required</div> 
    <p>Hello {{name}}!</p> 
    <div ng-form="test" id="test"> 
     <input type="text" name="firstName" ng-model="firstName" required> First name <br/> 
     <input id="field" name="field" required ng-model="field2" type="text"/> 
    </div> 
</body> 
<script> 
    var app = angular.module('plunker', []); 

    app.controller('MainCtrl', function($scope) { 
     $scope.name = 'World'; 
     $scope.field = "name"; 
     $scope.firstName = "FirstName"; 
     $scope.execute = function() { 
     alert('Executed!'); 
     } 
    }); 

</script> 

+0

這與http://stackoverflow.com/a/25342654/2333214有什麼不同?如果是這樣,你可以添加一個解釋它是如何不同? –

0

大廈西爾維奧·盧卡斯的回答,如果你迭代的循環,需要能夠插值形式的名稱和有效狀態:

<div 
    name="{{propertyName}}" 
    ng-form="" 
    class="property-edit-view" 
    ng-class="{ 
    'has-error': {{propertyName}}.editBox.$invalid, 
    'has-success': 
     {{propertyName}}.editBox.$valid && 
     {{propertyName}}.editBox.$dirty && 
     propertyValue.length !== 0 
    }" 
    ng-switch="schema.type"> 
    <input 
    name="editBox" 
    ng-switch-when="int" 
    type="number" 
    ng-model="propertyValue" 
    ng-pattern="/^[0-9]+$/" 
    class="form-control"> 
    <input 
    name="editBox" 
    ng-switch-default="" 
    type="text" 
    ng-model="propertyValue" 
    class="form-control"> 
    <span class="property-type" ng-bind="schema.type"></span> 
</div>