binding the model value of Twitter Bootstrap datepicker in controller in Angular js

前端 未结 1 489
粉色の甜心
粉色の甜心 2021-01-14 08:26

I am building an application with Angular.js and Twitter Bootstrap.

HTML:

 
相关标签:
1条回答
  • 2021-01-14 09:21

    Your bootstrap datepicker is a 3rd-component outside of angular. When you change your date from the datepicker, angular is not aware of the changes.

    You have to write a custom directive like this:

    app.directive('datepicker', function() {
        return {
    
          restrict: 'A',
          // Always use along with an ng-model
          require: '?ngModel',
    
          link: function(scope, element, attrs, ngModel) {
            if (!ngModel) return;
    
            ngModel.$render = function() { //This will update the view with your model in case your model is changed by another code.
               element.datepicker('update', ngModel.$viewValue || '');
            };
    
            element.datepicker().on("changeDate",function(event){
                scope.$apply(function() {
                   ngModel.$setViewValue(event.date);//This will update the model property bound to your ng-model whenever the datepicker's date changes.
                });
            });
          }
        };
    });
    

    Apply the directive to html:

    <div class="input-append date" datepicker ng-model="eventdate" data-date-format="dd-mm-yyyy">
         <input class="span2" size="20" type="text" required="" />
         <span class="add-on">
            <i class="icon-th"></i>
         </span>
     </div>
    

    DEMO

    0 讨论(0)
提交回复
热议问题