在角JS控制器绑定Twitter的引导日期选择器的模型值 [英] binding the model value of Twitter Bootstrap datepicker in controller in Angular js

查看:104
本文介绍了在角JS控制器绑定Twitter的引导日期选择器的模型值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我建设有Angular.js和Twitter的引导的应用程序。

I am building an application with Angular.js and 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.event); prints the data entered in event text box.

的console.log($ scope.eventdate); 打印未定义当我选择从日期选择器的日期

But console.log($scope.eventdate); prints "undefined" when I select a date from the date picker

可能是什么原因?

请咨询。

推荐答案

您引导日期选择器是角之外的第三个组件。当您从日期选择器更改日期,棱角分明是不知道的变化。

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

应用指令HTML:

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>

演示

这篇关于在角JS控制器绑定Twitter的引导日期选择器的模型值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆