AngularJS Directives - custom directives

AngularJS can be used to define custom directives to use in markup as element or attribute.

by aubz88

HTML

<body ng-app="hello">

  <div ng-controller="CustomDirectiveController">

    <h3>Developing and using custom directives</h3>

    <form name="form.mainForm">

      <div>
        <span>Effective Date: </span>
        <input required type="date" name="effectiveDate" ng-model="effectiveDate" />

        <div>
          <span>Expiry Date: </span>
          <input 
            type="date" 
            name="expiryDate" 
            ng-model="expiryDate" 
            date-greater-than="{{ effectiveDate }}" />
        </div>
      </div>

      <div ng-messages="form.mainForm.effectiveDate.$error">
        <div class="form-error" ng-message="required">
          <span>Effective date required</span>
        </div>
      </div>

      <div ng-messages="form.mainForm.expiryDate.$error">
        <div class="form-error" ng-message="dateGreaterThan">
          <span>expiry date must come after effective date</span>
        </div>
      </div>

      <pre>form.mainForm.$error = {{ form.mainForm.$error | json }}</pre>

    </form>
    
  </div>

</body>

CSS

.form-error {
  color: red;
}

JavaScript

var app = angular.module("hello", []);
  
  app.controller('CustomDirectiveController', function ($scope) {
  
  	$scope.exppiryDate = null;
    $scope.effectiveDate = null;
  
  });

  app.directive('dateGreaterThan', function () {
      return {
 				restrict: 'A',
        require: 'ngModel',
        scope: false,
        link: function (scope, elm, attrs, ctrl) {
            console.log(' here we are ');

            function isValidDateRange(expiryDate, effectiveDate) {

                console.log(expiryDate, effectiveDate);

                if (effectiveDate == null || expiryDate == null ) {
                    return true;
                }

                return effectiveDate > expiryDate;
            }

            function validateDateRange(inputValue) {
                var expiryDate = inputValue;
                var effectiveDate = scope.effectiveDate;
                var isValid = isValidDateRange(expiryDate, effectiveDate);
                console.log("isValid: ", isValid);
                ctrl.$setValidity('dateGreaterThan', isValid);
                return inputValue;
            }

            ctrl.$parsers.unshift(validateDateRange);
            ctrl.$formatters.push(validateDateRange);
            attrs.$observe('dateGreaterThan', function () {
                validateDateRange(ctrl.$viewValue);
            });
      }
      };
  });