Last active
August 29, 2015 14:02
-
-
Save ninjasort/ceced2c313f31232a512 to your computer and use it in GitHub Desktop.
CrowdSurge Date of Birth Directive
This file contains 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
<ng-form name="date_of_birth" class="form-inline cs-dob" ng-class="{'has-error': date_of_birth.$invalid && submitted}"> | |
<div class="form-group"> | |
<select name="month" class="form-control" ng-model="dob.month" ng-options="n for n in [] | range:1:12" required> | |
<option value="">MM</option> | |
</select> | |
</div> | |
<div class="form-group"> | |
<select name="day" class="form-control" ng-model="dob.day" ng-options="n for n in [] | range:1:31" required> | |
<option value="">DD</option> | |
</select> | |
</div> | |
<div class="form-group"> | |
<select name="year" class="form-control" ng-model="dob.year" ng-options="n for n in [] | range:1898:2014:true" required> | |
<option value="">YYYY</option> | |
</select> | |
</div> | |
<div ng-if="date_of_birth.$error.required && submitted"> | |
<p class="help-block">Date of Birth is required.</p> | |
</div> | |
<div ng-if="date_of_birth.$error.validAge && submitted"> | |
<p class="help-block">You must be {{ageLimit}}</p> | |
</div> | |
</ng-form> |
This file contains 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
'use strict'; | |
angular.module('<%= _.camelize(_.slugify(appName)) %>.directives') | |
.directive('csDob', ['$compile', | |
function ($compile) { | |
return { | |
require: 'ngModel', | |
restrict: 'E', | |
templateUrl: 'html/partials/tpl/_cs-dob.html', | |
replace: true, | |
scope: { | |
submitted: '=onSubmit', | |
dob: '=ngModel' | |
}, | |
link: function (scope, el, attrs, ctrl) { | |
scope.ageLimit = parseInt(attrs.ageLimit); | |
var schema = { | |
year: '', | |
month: '', | |
day: '' | |
}, | |
dob = [], | |
date; | |
scope.$watch('dob', function () { | |
if (!scope.date_of_birth.$error.required) { | |
dob = []; | |
if (angular.isObject(scope.dob)) { | |
for (var k in schema) { | |
if (scope.dob[k] !== undefined) { | |
var dobCopy = angular.copy(scope.dob[k]); | |
dob.push(dobCopy += ''); | |
} | |
} | |
} | |
var _date = dob.join('-'); | |
if (_date !== '' && _date !== undefined) { | |
var now = moment(); | |
var birthday = moment(_date, 'YYYY-MM-DD'); | |
var age = now.diff(birthday, 'years'); | |
var validAge = age > scope.ageLimit; | |
if (validAge) { | |
ctrl.$setValidity('validAge', true); | |
} else { | |
ctrl.$setValidity('validAge', false); | |
} | |
} | |
} | |
}, true); | |
} | |
}; | |
} | |
]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment