0
我有一個<table>
其中每行有幾個input type="text"
。我想驗證輸入是否爲空,如果是,則將CSS類添加到此輸入字段,該字段將顯示錯誤。我在$scope
中得到的全部是$$hashKey
,我知道這是識別ng-repeat
列表元素的唯一值。
我怎麼能得到這個$$hashKey
?DOM對象?我正在使用開發工具進行挖掘,但我沒有找到它。
我有一個<table>
其中每行有幾個input type="text"
。我想驗證輸入是否爲空,如果是,則將CSS類添加到此輸入字段,該字段將顯示錯誤。我在$scope
中得到的全部是$$hashKey
,我知道這是識別ng-repeat
列表元素的唯一值。
我怎麼能得到這個$$hashKey
?DOM對象?我正在使用開發工具進行挖掘,但我沒有找到它。
而不是試圖從你的控制器(或服務)操縱DOM(即查找和元素和添加/刪除類),你應該從一個指令。
寫指令,將做驗證你:
.directive('validateField', function(){
return {
restrict: 'A',
require: 'ngModel',
link: function(scope, elem, attrs, ngModel){
scope.$watch(attrs.ngModel, function(newVal, oldVal){
var isValid = false;
// do some validation checking on newVal here
ngModel.$setValidity('tableInput', isValid);
});
}
};
});
如文檔here指出,該$setValidity
功能會自動添加一個類的元素對你來說,根據你提供力所能及的關鍵。在這種情況下,我們提供了'tableInput'
的密鑰,因此它將在模型無效時添加ng-invalid-table-input
類,並在模型有效時添加一類ng-valid-table-input
。
所以,你現在要做的就是創建一個規則有一些特殊的風格:
input.ng-invalid-table-input{
/* special styles go here */
}
input.ng-valid-table-input{
/* special styles go here */
}
然後你可以使用這個在你看來是這樣的:
<table>
<tr ng-repeat="things in listOfThings">
<td ng-repeat="thing in things">
<input type="text" ng-model="someValue" validate-field />
</td>
</tr>
</table>
然後,表中的任何輸入都將被動態(並自動)驗證並設置樣式。那有意義嗎?你必須修改上面的例子,但希望它指出你在正確的方向。
看起來很整潔,但它看起來像$ setValidity目前尚無穩定版本可用。我可以自己從指令中添加/刪除類嗎? – chachan
角度的當前「穩定」版本是1.0.8。以下是針對1.0.8的'$ setValidity()'的文檔:http://code.angularjs.org/1.0.8/docs/api/ng.directive:ngModel.NgModelController。所以你仍然可以在「穩定」版本中使用它。 – tennisgent