入力タイプの要素としてレンダリングされるカスタム ディレクティブを作成したいと考えています。ディレクティブは、angularjs 検証フレームワークを再利用する必要があります。以下は、custom-input
私が作成した実際のディレクティブです。
<!doctype html>
<html ng-app="validationApp">
<body>
<div class="container" ng-controller="ValidationController as validationController">
<form name="myForm">
{{employee | json}}
<custom-input ng-required="true" ng-model="employee.name" name="employee.name" id="employeeName" ng-pattern="/^[0-9]{1,7}$/"/></custom-input>
<span ng-show="myForm['employee.name'].$error.required">This is a required field</span>
<span ng-show="myForm['employee.name'].$error.pattern">This is a invalid field</span>
</form>
</div>
<script type="text/ng-template" id="/templates/customInput.html">
<div>
<input type="text" name="{{name}}" ng-model="newInput" id="{{id}}">
</div>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.6/angular.js"></script>
</body>
</html>
これに対応する JavaScript は次のとおりです。
angular.module('validationApp', [])
.controller("ValidationController", function(){
})
.directive("customInput", function(){
return {
restrict: "E",
require : "ngModel",
replace: "true",
templateUrl : "/templates/customInput.html",
scope : {
id : "@", //bind id to scope
name : "@" //bind name to scope
},
link: function(scope, element, attrs, ngModelCtrl){
//When newInput is updated, update the model of original input
scope.$watch('newInput', function(newValue){
ngModelCtrl.$setViewValue(newValue);
});
//On first load, get the initial value of original input's model and assign it to new input's model
ngModelCtrl.$render = function(){
var viewValue = ngModelCtrl.$viewValue;
if(viewValue){
scope.newInput = viewValue;
}
}
}
}
});
このカスタム入力に適用ng-required
して検証しようとしています。ng-pattern
私は2つの問題に直面しています:
- angularjs 1.2.6 では
ng-required
検証を実行できますcustom-input
が、1.3.0 では検証が実行されません。 ng-pattern
両方のバージョンで検証を開始できません。
私の理解では、すべて$setViewValue
のngModelController
検証が開始されます。上記は不自然な例です。私の実際の使用例は、SSN の 3 つの入力ボックスをレンダリングするカスタム ディレクティブを作成することです。
以下は、それぞれ 1.2.6 と 1.3.0 のプランカー リンクです。