<!DOCTYPE html>
<html ng-app="siteApp">

  <head>
       <script data-require="jquery@2.2.0" data-semver="2.2.0" src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  
    <link data-require="bootstrap@3.3.7" data-semver="3.3.7" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script data-require="bootstrap@3.3.7" data-semver="3.3.7" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script data-require="angular.js@1.5.8" data-semver="1.5.8" src="https://code.angularjs.org/1.5.8/angular.js"></script>
  
  </head>

  <body>
    
    <link rel="stylesheet" href="style.css" />
    <script src="script.js"></script>
    <form ng-submit="submit()" class="form-horizontal" novalidate="" name="Wizard1_Form" >
      <div class="form-group" ng-controller="mainController" >
        <div class="col-xs-12  input-holder " ng-class="{'dd-disabled':birthDate ,'has-value': birthDate}">
          <div class="clearfix bd-pane">
            <label for="birthDate" class="lbl inline-lbl" birthdate<="" label="">
              <input rsmdatedropdowns="" is-required="true" name="birthDate" ng-model="birthDate" />
            </label>
          </div>
        </div>
      </div>
    </form>
    <script src="app.js"></script>
    <script src="dirModal.js"></script>
    <script src="mainController.js"></script>
    <script src="rsmdatedropdowns.js"></script>
    <script src="dirDropdownModal.js"></script>
  </body>

</html>
// Code goes here

/* Styles go here */

(function () {
  'use strict';
  var dd = angular.module('rorymadden.date-dropdowns', []);

  dd.factory('rsmdateutils',['$timeout', function ($timeout) {
    var that = this,
        dayRange = [1, 31],
        months = [
          '',
          'January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December'
        ];

    function changeDate (date) {
      if(date.day > 28) {
        date.day--;
        return date;
      } else if (date.month > 11) {
        date.day = 31;
        date.month--;
        return date;
      }
    };

    return {
        checkDate: function (date) {
           
                var d;
                if (!date.day || date.month === null || date.month === undefined || !date.year) return false;

                d = new Date(Date.UTC(date.year, date.month -1, date.day));

                if (d && (d.getMonth() === date.month -1 && d.getDate() === Number(date.day))) {
                    return d;
                }
                
                return this.checkDate(changeDate(date));
            
      },
      days: (function () {
        var days = [];
        while (dayRange[0] <= dayRange[1]) {
            var val = dayRange[0]++;
            days.push({ id: val, name: val });
          //days.push(dayRange[0]++);
        }
        //console.log(days);
        return days;
      }()),
      months: (function () {
        var lst = [],
            mLen = months.length;

        for (var i = 0; i < mLen; i++) {
          lst.push({
            id: i,
            name: months[i]
          });
        }
        return lst;
      }())
    };
  }])

  dd.directive('rsmdatedropdowns', ['rsmdateutils', function (rsmdateutils) {
    return {
      restrict: 'A',
      replace: true,
      require: 'ngModel',
      scope: {
          model: '=ngModel',
          isRequired: '=',
          ngDisabled: '=',
          hideDay: '=',
          name: '@'
      },
      controller: ['$scope', 'rsmdateutils', '$filter', '$timeout', function ($scope, rsmDateUtils, $filter, $timeout) {
        $scope.days = rsmDateUtils.days;
        $scope.months = rsmDateUtils.months;
        $scope.dateFields = {};
        if ($scope.hideDay) {
            $scope.dateFields.day = 1;
        } else {
            $scope.dateFields.day = new Date($scope.model).getUTCDate();
        }
        $scope.dateFields.month = new Date($scope.model).getUTCMonth() + 1;
        $scope.dateFields.year = new Date($scope.model).getUTCFullYear();

        // Initialize with current date (if set)
        $scope.$watch('model', function (newDate) {
            //BUG:: here the bug on change the filter search year this code apply
            if (newDate) {
                if ($scope.hideDay) {
                    $scope.dateFields.day = 1;
                } else {
                    $scope.dateFields.day = new Date(newDate).getUTCDate();
                }

                $scope.dateFields.month = new Date(newDate).getUTCMonth() +1;

                $scope.dateFields.year = new Date(newDate).getUTCFullYear();
            } else {
              console.log("here the error ");
                if ($scope.hideDay) {
                    $scope.dateFields.day = 1;
                } else {
                  $scope.dateFields.day = null;
                }
                $scope.dateFields.month = null;
                $scope.dateFields.year = null;
            }
        });

        $scope.checkDate = function () {
            $timeout(function () {
                var date = rsmDateUtils.checkDate($scope.dateFields);
                if (date) {
                    if ($scope.hideDay) {
                        $scope.model = $filter('date')(date, 'yyyy-MM');
                    } else {
                        $scope.model = $filter('date')(date, 'yyyy-MM-dd');
                    }

                }
            });
        };
      }],
      template:
      '<div class="date-ddl ">{{dateFields|json}}' +
      '<div ng-if="!hideDay" class="f-cont num-txt input-holder inside" ng-class="{\'has-value\':dateFields.day}" ><dir-dropdown-modal   ng-disabled="ngDisabled" name="dateFields.day_{{name}}" ng-model="dateFields.day" is-required="isRequired" title="Day" ng-change="checkDate()" list="days"></dir-dropdown-modal></div>' +
      // '     <select ng-if="!hideDay" ng-required="isRequired" name="dateFields.day" ng-disabled="ngDisabled" data-ng-model="dateFields.day" placeholder="יום" class="sel  sel-day num-txt" ng-options="day for day in days" ng-change="checkDate()">  <option value="">יום</option></select>' +
      '<div class="f-cont input-holder inside" ng-class="{\'has-value\':dateFields.month || dateFields.month==0}"><dir-dropdown-modal   name="dateFields.month_{{name}}"  ng-disabled="ngDisabled" ng-model="dateFields.month" is-required="isRequired" title="Month" ng-change="checkDate()" list="months"></dir-dropdown-modal></div>' +
      //'    <select name="dateFields.month" ng-required="isRequired" ng-disabled="ngDisabled" data-ng-model="dateFields.month" placeholder="חודש" class="sel  sel-month" ng-options="month.value as month.name for month in months" value="{{ dateField.month }}" ng-change="checkDate()" >  <option value="">חודש</option></select>' +
     '<div ng-show="!yearText"  class="f-cont num-txt m-r-0 input-holder inside" ng-class="{\'has-value\':dateFields.year}"><dir-dropdown-modal   name="dateFields.year_{{name}}" ng-disabled="ngDisabled" ng-model="dateFields.year" is-required="isRequired" title="Year" ng-change="checkDate()" list="years"></dir-dropdown-modal></div>' +
      //'    <select ng-show="!yearText" ng-required="isRequired" ng-disabled="ngDisabled" name="dateFields.year" data-ng-model="dateFields.year" placeholder="שנה" class="sel sel-sel-year  num-txt" ng-options="year for year in years" ng-change="checkDate()" >  <option value="">שנה</option></select>' +
      //'    <input ng-show="yearText" ng-required="isRequired" type="text" name="dateFields.year" ng-disabled="ngDisabled"  data-ng-model="dateFields.year" placeholder="Year" class="sel " >' +
      '  <input name="{{name}}" type="hidden" ng-disabled="ngDisabled" ng-model="model" ng-required="isRequired" />' +
      '</div>',
      link: function (scope, element, attrs, ctrl) {
        var currentYear = parseInt(attrs.startingYear, 10) || new Date().getFullYear(),
            numYears = parseInt(attrs.numYears,10) || 100,
            oldestYear = currentYear - numYears,
            overridable = [
              'dayDivClass',
              'dayClass',
              'monthDivClass',
              'monthClass',
              'yearDivClass',
              'yearClass'
            ],
            required;

        scope.years = [];
        scope.yearText = attrs.yearText ? true : false;

        //if (attrs.ngDisabled) {
        //  scope.$parent.$watch(attrs.ngDisabled, function (newVal) {
        //    scope.disableFields = newVal;
        //  });
        //}

        if (attrs.required) {
          required = attrs.required.split(' ');

          ctrl.$parsers.push(function (value) {
            angular.forEach(required, function (elem) {
              if (!angular.isNumber(elem)) {
                ctrl.$setValidity('required', false);
              }
            });
            ctrl.$setValidity('required', true);
          });
        }

        for (var i = currentYear; i >= oldestYear; i--) {
            scope.years.push({ id: i, name: i });
        }

        (function () {
          var oLen = overridable.length,
              oCurrent,
              childEle;
          while (oLen--) {
            oCurrent = overridable[oLen];
            childEle = element[0].children[Math.floor(oLen / 2)];

            if (oLen % 2 && oLen != 2) {
              childEle = childEle.children[0];
            }

            if (attrs[oCurrent]) {
              angular.element(childEle).attr('class', attrs[oCurrent]);
            }
          }
        }());
      }
    };
  }]);
}());
siteApp.directive('dirDropdownModal', ['$timeout',  '$filter',  function ($timeout,  $filter) {
    return {
        restrict: 'E',
        templateUrl:  'dirDropdownModal.html',
        scope: {
            ngModel: '=',
            ngDisabled: '=',
            isRequired: '=',
            list: '=',
            name: '@',
            title: '@',
            ngChange: '&',
            ajaxCall: '=',
            limits: '@',
            hideLable: '='
        },
        require: 'ngModel',
        link: function (scope, element, attr, ctrl) {
            scope.loadData = false;
            scope.showModal = false;
            scope.search = {};
            scope.opened = false;
            scope.modalOneShown = function () {
                //console.log('model one shown');
                
            }

            scope.modalOneHide = function () {
                //console.log('model one hidden');
            }


            scope.text = "";
           
            scope.selectElement = function (item) {
                $timeout(function () {
                    scope.ngModel = item.id;
                    scope.text = item.name;
                    scope.showModal = false;
                    scope.ngChange();
                });
            }


            scope.openModal = function (req) {
                if (scope.ngDisabled) return;
                if (req || !scope.ngModel || !scope.showModal) {
                    scope.showModal = true;
                    if (!scope.opened) {
                        scope.opened = true;
                    }
                }

            }

            scope.removeLimits = function () {
                scope.limits = 999999;
            }

            scope.txtClick = function (keyEvent) {
                if (keyEvent.which === 13)
                    scope.openModal(true);
            }

            scope.clearFilter = function () {
                scope.search.name = "";
            }

            var init = function () {
                scope.loadData = false;
               
                if (scope.ngModel && scope.list && scope.list.length > 0) {
                   
                    var item_in_array = $filter("filter")(scope.list, { id: scope.ngModel }, true);
                    
                    if (item_in_array.length > 0) {
                        scope.text = item_in_array[0].name;
                    } else {
                        scope.ngModel = null;
                        scope.text = "";
                    }
                }
                if (scope.ajaxCall && (scope.list == null || scope.list.length == 0)) {
                    scope.loadData = true;
                }


               

            }
            var listener = scope.$watch(
                function () {
                    return scope.list;
                }, function (newValue, oldValue) {
                    $timeout(function () {
                       
                            init();
                            if (!scope.ajaxCall && scope.list && scope.list.length > 0) {
                                listener();
                            }
                        });


                   
                }, true);

            var listener2 = scope.$watch(
               function () {
                   return scope.ngModel;
               }, function (newValue, oldValue) {
                     
                      if (scope.ngModel) {
                       
                          $timeout(function () {
                              
                           init();
                           listener2();
                       },0);


                   }
               }, true);




        }
    }
}]

);

siteApp.directive('modal', function () {
    return {
        template: '<div class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true"><div class="vertical-alignment-helper"><div class="modal-dialog vertical-align-center modal-sm"><div class="modal-content" ng-transclude><div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title" id="myModalLabel">Modal title</h4></div></div></div></div></div>',
        restrict: 'E',
        transclude: true,
        replace: true,
        scope: { visible: '=', onSown: '&', onHide: '&' },
        link: function postLink(scope, element, attrs) {

            $(element).modal({
                show: false,
                keyboard: attrs.keyboard,
                backdrop: attrs.backdrop
            });

            scope.$watch(function () { return scope.visible; }, function (value) {

                if (value == true) {
                    $(element).modal('show');
                } else {
                    $(element).modal('hide');
                }
            });

            $(element).on('shown.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attrs.visible] = true;
                });
            });

            $(element).on('shown.bs.modal', function () {
                scope.$apply(function () {
                    scope.onSown({});
                });
            });

            $(element).on('hidden.bs.modal', function () {
                scope.$apply(function () {
                    scope.$parent[attrs.visible] = false;
                });
            });

            $(element).on('hidden.bs.modal', function () {
                scope.$apply(function () {
                    scope.onHide({});
                });
            });
        }
    };
}
);

siteApp.directive('modalHeader', function () {
    return {
        template: '<div class="modal-header"><button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button><h4 class="modal-title">{{title}}</h4></div>',
        replace: true,
        restrict: 'E',
        scope: { title: '@' }
    };
});

siteApp.directive('modalBody', function () {
    return {
        template: '<div class="modal-body" ng-transclude></div>',
        replace: true,
        restrict: 'E',
        transclude: true
    };
});

siteApp.directive('modalFooter', function () {
    return {
        template: '<div class="modal-footer" ng-transclude></div>',
        replace: true,
        restrict: 'E',
        transclude: true
    };
});
<div class="dd-modal" ng-class="{'xloading-d':loadData, 'has-value': ngModel }">
    <input id="{{name}}" ng-required="isRequired" ng-disabled="ngDisabled" placeholder="{{(hideLable)?title:''}}" ng-focus="openModal(false)" readonly ng-model="text" ng-keyup="txtClick($event)" ng-click="openModal(true)" type="text" autocomplete="off" class="txt" />
    <label for="{{name}}" class="lbl" ng-show="!hideLable">{{title}}</label>
    <input name="{{name}}" type="hidden" ng-model="ngModel" ng-required="isRequired" />
</div>
<modal visible="showModal" on-sown="modalOneShown()" on-hide="modalOneHide()">
    <modal-header class="font-18 font-bold" title="{{title}}"></modal-header>
    <modal-body>
        <div class="dd-modal-body">
            <div class="free-wrapper">
                <input class="free-txt" ng-model="search.name" placeholder="Free search" />

                <i ng-hide="search.name" class="mdi mdi-filter "></i>
                <i ng-click="clearFilter()" ng-show="search.name" class="mdi mdi-filter-remove "></i>

            </div>
            <div class="dd-modal-data cutomScrollbar" ng-if="opened">
                <button ng-show="item.name" type="button" ng-class="{'selected': ngModel == item.id}" class="dd-modal-item" ng-repeat="item in list | filter:search |limitTo:limits" ng-click="selectElement(item)">
                    {{item.name}}
                </button>

                <button type="button" ng-show="limits!= null && limits> 0 && limits < list.length" class="site-btn text-center color-reg" ng-click="removeLimits()">
                   show all
                </button>
            </div>
        </div>
    </modal-body>
    <modal-footer>
        <button type="button" class="site-btn-link" data-dismiss="modal">ביטול</button>
        <!--<button type="button" class="site-btn-link color-main"  class="">חדש</button>-->
    </modal-footer>
</modal>

var siteApp = angular.module('siteApp',['rorymadden.date-dropdowns']);
siteApp.controller('mainController', ['$scope', function ($scope) {
  
 

   

}]);