angularjs - 在 Angular js 的 Controller 中绑定(bind) Twitter Bootstrap datepicker 的模型值

标签 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>

Controller :

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); 打印“未定义”

可能是什么原因?

请指教。

最佳答案

您的 Bootstrap 日期选择器是 Angular 之外的第三个组件。当您从日期选择器更改日期时,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

关于angularjs - 在 Angular js 的 Controller 中绑定(bind) Twitter Bootstrap datepicker 的模型值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21397361/

相关文章:

jquery - 如何在 "navbar"的navbar品牌下设置一个inline form占100%宽度

javascript - JQuery 日期选择器设置默认值

json - 获取没有时间/时区的 ui.bootstrap.datepicker 值

jquery - ASP.NET MVC3 : Displaying Date in correct format with JQuery DatePicker and editorFor/TextBoxFor

angularjs - 在模板中使用指令 Controller 方法

javascript - Angular js路由在本地主机中不起作用

php - 在 AngularJS 应用程序中正确包含 WordPress 博客的策略

javascript - 嵌套模板上的 Angular js 范围

html - Bootstrap 3 五列响应固定高度和宽度

html - Bootstrap "errors"- 这些重要吗?