Created
July 11, 2014 13:26
-
-
Save aya-eiya/fb65044f986d4ccff22d to your computer and use it in GitHub Desktop.
AngularJSのカスタムバリデーションをモジュールに登録して使いまわす方法 ref: http://qiita.com/aya_eiya/items/75d558f1fc1198fa137f
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="ja"><head><meta charset="utf-8" /></head> | |
<body> | |
<div ng-app="app" ng-controller="confirmCtrl"> | |
<form name="form" novalidate> | |
<div> | |
<input type="text" ng-model="target" name="target" /> | |
<input type="text" ng-model="targetConfirm" name="targetConfirm" | |
confirm="target" | |
/> | |
</div> | |
<p ng-show="form.targetConfirm.$error.confirm">password confirmation invalid</p> | |
<button ng-disable="form.$invalid">button</button> | |
</form> | |
</div> | |
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.js"></script> | |
<script> | |
// commonUI.js | |
angular.module('commonUI',[]). | |
factory('validationUtils',[function(){ | |
return { | |
confirm : { | |
require : 'ngModel', | |
scope : false, | |
link : function(scope,elm,attr,ctrl){ | |
var confirm = function (viewValue) { | |
var form = 'form'; | |
if(elm.length){ | |
form = elm[0].form.name; | |
}else if(elm.context){ | |
form = elm.context.form.name; | |
} | |
var valid = viewValue != scope[form][attr.confirm].$viewValue; | |
ctrl.$setValidity('confirm', !valid); | |
if(!valid){ return viewValue; } | |
}; | |
ctrl.$parsers.unshift(confirm); | |
ctrl.$formatters.unshift(confirm); | |
} | |
} | |
}; | |
}]); | |
</script> | |
<script> | |
// app.js | |
var app = angular.module('app', ['commonUI']); | |
app.controller('confirmCtrl',['$scope',function ($scope) { | |
$scope.target = 'abcd'; | |
$scope.targetConfirm = 'abcd'; | |
}]); | |
app.directive('confirm',['validationUtils',function(validationUtils){ | |
return validationUtils.confirm; | |
}]); | |
</script> | |
</body></html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment