在Angular js中绑定控制器中Twitter Bootstrap datepicker的模型值

时间:2014-01-28 05:13:14

标签: angularjs twitter-bootstrap datepicker

我正在使用Angular.js和Twitter Bootstrap构建一个应用程序。

HTML:

 <div ng-controller="myController"> 
 <label for="event">Event</label>
 <input type="text" ng-model="event"/>
 <label for="eventdate">Date</label>
 <div class="input-append date" id="datepicker" data-date-format="dd-mm-yyyy">
 <input class="span2" size="20" type="text" id="datepicker" ng-model="eventdate" required>
 <span class="add-on"><i class="icon-th"></i></span>
 <input class="btn-primary" type="submit" id="submit" value="Submit" ng-click="submit()" />
 </div>

控制器:

var myApp1 = angular.module('myApp1', []);
myApp1.controller('myController', function($scope) {
$('#datepicker').datepicker();
$scope.submit = function () {
console.log($scope.event);
console.log($scope.eventdate);
};
});

当我点击“提交”按钮时,

console.log($scope.event);打印在事件文本框中输入的数据。

但是当我从日期选择器中选择日期时,console.log($scope.eventdate);会打印“未定义”

可能是什么原因?

请建议。

1 个答案:

答案 0 :(得分:7)

你的bootstrap datepicker是angular之外的第3个组件。当您从datepicker更改日期时,angular不知道更改。

你必须写一个这样的自定义指令:

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.
            });
        });
      }
    };
});

将指令应用于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