2016-12-13 67 views
0

我想切換輸入css類如果驗證有效,我可以做如果無效,但我需要兩個類如果是有效的,如果不是。它是容易使,如果是無效的,但如何添加,如果是有效的,這裏是我的代碼,我現在:如果驗證是有效的輸入角度切換類

<form name="userForm" ng-submit="submitForm()" novalidate> 
    <input type="email" name="email" placeholder="E-mailadres" class="input-field" ng-model="user.email" required ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine }" /> 
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p> 
    <input type="password" name="password" ng-model="user.password" placeholder="Wachtwoord" class="input-field" required /> 
    <p ng-show="userForm.password.$invalid && !userForm.password.$pristine" class="help-block">You name is required.</p> 
    <button type="submit" class="btn hit-btn" ng-disabled="userForm.$invalid">Log in</button> 
</form> 

你會發現,我有類有錯誤,但我需要也類沒有錯誤

回答

1

試試這個...

.has-error { 
 
    background: red; 
 
} 
 
.no-error { 
 
    background: green; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script> 
 
<div ng-app> 
 
    <form name="userForm" ng-submit="submitForm()" novalidate> 
 
    <input type="email" name="email" placeholder="E-mailadres" class="input-field" ng-model="user.email" required ng-class="{ 'has-error' : userForm.email.$invalid && !userForm.email.$pristine,'no-error' :!userForm.email.$invalid }" /> 
 
    <p ng-show="userForm.email.$invalid && !userForm.email.$pristine" class="help-block">Enter a valid email.</p> 
 
    <input type="password" name="password" ng-model="user.password" placeholder="Wachtwoord" class="input-field" required /> 
 
    <p ng-show="userForm.password.$invalid && !userForm.password.$pristine" class="help-block">You name is required.</p> 
 
    <button type="submit" class="btn hit-btn" ng-disabled="userForm.$invalid">Log in</button> 
 
    </form> 
 
</div>

+0

這工作正常,txanks –

+0

永遠歡迎:) – Sankar

1

如果您需要另一個類,只是相反的條件添加:

<input type="email" name="email" placeholder="E-mailadres" 
    class="input-field" ng-model="user.email" required 
    ng-class="{ 
    'has-error' : userForm.email.$invalid && !userForm.email.$pristine, 
    'no-error' : !userForm.email.$invalid || userForm.email.$pristine 
    }" 
/> 
+0

這不工作,現在甚至已經異常未apllied? –

+0

@MiomirDancevic對不起,我有一個虛假的''',沒有它,再試一次。 – Duncan

0
ng-class="{userForm.email.$invalid && !userForm.email.$pristine?'has-error':'no-error'}" 
+0

這不工作,現在甚至有錯誤不能解決? –

+0

你定義了兩個類嗎? https://scotch.io/tutorials/the-many-ways-to-use-ngclass 三元運算符應該工作。 – Sunny