jQuery 如何将 Bootstrap-datepicker 元素与 angularjs ng-model 绑定?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19316937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 23:40:18  来源:igfitidea点击:

how to bind Bootstrap-datepicker element with angularjs ng-model?

javascriptjquerytwitter-bootstrapangularjsdatepicker

提问by Deepankar Bajpeyi

Here is the html for the date field :

这是日期字段的html:

<div class='form-group'>
  <label>Check out</label>
    <input type='text' ng-model='checkOut' class='form-control' data-date-format="yyyy-mm-dd" placeholder="Check out" required id="check-out">
</div>
<script>
$('#check-out').datepicker();
</script>

The datepicker shows up in the input field. However if I do this in my controller :

日期选择器显示在输入字段中。但是,如果我在控制器中执行此操作:

console.log($scope.checkOut);

I get undefined in the javascript console. How to solve this ?
Is there a better way to use bootstrap-datepickerwith angularjs?

我明白了undefined in the javascript console。如何解决这个问题?
有没有办法使用更好的方法bootstrap-datepickerangularjs

I don't want to use angular-ui/angular-strapsince my project is bloated with javascript libraries.

我不想使用,angular-ui/angular-strap因为我的项目充斥着 javascript 库。

采纳答案by michaelpoltorak

As @lort suggests, you cannot access the datepicker model from your controller because the datepicker has its own private scope.

正如@lort 所建议的,您无法从控制器访问 datepicker 模型,因为 datepicker 有自己的私有范围。

If you set: ng-model="parent.checkOut"

如果你设置: ng-model="parent.checkOut"

and define in the controller: $scope.parent = {checkOut:''};

并在控制器中定义: $scope.parent = {checkOut:''};

you can access the datepicker using: $scope.parent.checkOut

您可以使用以下方法访问日期选择器: $scope.parent.checkOut

回答by Sreekanth Karini

I am using bootstrap 3 datepicker https://eonasdan.github.io/bootstrap-datetimepicker/and angularjs, I had the same problem with ng-model, so I am getting input date value using bootstrap jquery function, below is the code in my controller, it's worked for me.

我正在使用 bootstrap 3 datepicker https://eonasdan.github.io/bootstrap-datetimepicker/和 angularjs,我对 ng-model 有同样的问题,所以我使用 bootstrap jquery 函数获取输入日期值,下面是代码我的控制器,它对我有用。

Html

html

<input class="form-control" name="date" id="datetimepicker" placeholder="select date">

Controller

控制器

$(function() {

    //for displaying datepicker

    $('#datetimepicker').datetimepicker({
        viewMode: 'years',
        format: 'DD/MM/YYYY',
    });

    //for getting input value

    $("#datetimepicker").on("dp.change", function() {

        $scope.selecteddate = $("#datetimepicker").val();
        alert("selected date is " + $scope.selecteddate);

    });

 });

回答by Angelo Ortega

I am using Angular JS 1.5.0 and Bootstrap 3 Datetimepicker from https://eonasdan.github.io/bootstrap-datetimepicker/

我正在使用来自https://eonasdan.github.io/bootstrap-datetimepicker/ 的Angular JS 1.5.0 和 Bootstrap 3 Datetimepicker

After some time and struggling, I finally found a solution how to make it work for me :)

经过一段时间和挣扎,我终于找到了一个解决方案,如何让它为我工作:)

JSFiddle: http://jsfiddle.net/aortega/k6ke9n2c/

JSFiddle:http: //jsfiddle.net/aortega/k6ke9n2c/

HTML Code:

HTML代码:

  <div class="form-group col-sm-4" >
     <label for="birthdate" class="col-sm-4">Birthday</label>
     <div class="col-sm-8">
       <div class="input-group date" id="birthdate"  ng-model="vm.Birthdate" date-picker>
         <input type="text" class="form-control netto-input"  ng-model="vm.Birthdate" date-picker-input>

         <span class="input-group-addon">
           <span class="glyphicon glyphicon-calendar"></span>
         </span>
       </div>
     </div>
  </div>
 <div class="form-group col-sm-4">
     <label for="birthdateText" class="col-sm-4">Model:</label>
     <div class="col-sm-8">
         <input type="text" class="form-control netto-input"  ng-model="vm.Birthdate">
     </div>
  </div>
</body>

App.js:

应用程序.js:

Simply a controller setting the viewmodels Birtdate attribute:

只是一个设置 viewmodels Birtdate 属性的控制器:

var app = angular.module('exampleApp',[]);

app.controller('ExampleCtrl',  ['$scope', function($scope) {
    var vm = this;
    vm.Birthdate = "1988-04-21T18:25:43-05:00";
}]);

The first directive is initializing the datetimepickerand listening to the dp.change event.

第一个指令是初始化datetimepicker并监听 dp.change 事件。

When changed - the ngModel is updated as well.

更改时 - ngModel 也会更新。

// DatePicker -> NgModel
app.directive('datePicker', function () {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
            $(element).datetimepicker({
                locale: 'DE',
                format: 'DD.MM.YYYY',
                parseInputDate: function (data) {
                    if (data instanceof Date) {
                        return moment(data);
                    } else {
                        return moment(new Date(data));
                    }
                },
                maxDate: new Date()
            });

            $(element).on("dp.change", function (e) {
                ngModel.$viewValue = e.date;
                ngModel.$commitViewValue();
            });
        }
    };
});

The second directive is watching the ngModel, and triggering the input onChange event when changed. This will also update the datetimepickerview value.

第二个指令是观察 ngModel,并在更改时触发输入 onChange 事件。这也将更新datetimepicker视图值。

// DatePicker Input NgModel->DatePicker
app.directive('datePickerInput', function() {
    return {
        require: 'ngModel',
        link: function (scope, element, attr, ngModel) {
            // Trigger the Input Change Event, so the Datepicker gets refreshed
            scope.$watch(attr.ngModel, function (value) {
                if (value) {
                    element.trigger("change");
                }
            });
        }
    };
});

回答by user5045936

I just found a solution to this myself. I just pass in the model name to the directive (which I found most of online). This will set the value of the model when the date changes.

我自己刚刚找到了解决方案。我只是将模型名称传递给指令(我在网上找到了大部分)。这将在日期更改时设置模型的值。

<input data-ng-model="datepickertext" type="text" date-picker="datepickertext" />{{datepickertext}}    

angular.module('app').directive('datePicker', function() {
    var link = function(scope, element, attrs) {
        var modelName = attrs['datePicker'];
        $(element).datepicker(
            {
                onSelect: function(dateText) {
                    scope[modelName] = dateText;
                    scope.$apply();
                }
            });
    };
    return {
        require: 'ngModel',
        restrict: 'A',
        link: link
    }
});

回答by NeshaSerbia

I have the same problem and resolve like this

我有同样的问题并像这样解决

added in html part

添加在 html 部分

<input class="someting" id="datepicker" type="text" placeholder="Dae" ng-model=""/>

and simple in Controller call

和简单的控制器调用

$scope.btnPost = function () {

          var dateFromHTML = $('#datepicker').val();

回答by Jon Snow

Have you tried AngularUI bootstrap? It has all the bootstrap modules rewritten in angular(including datepicker): http://angular-ui.github.io/bootstrap/

您是否尝试过 AngularUI 引导程序?它具有以 angular 重写的所有引导程序模块(包括日期选择器):http: //angular-ui.github.io/bootstrap/

回答by xonya

Using thisdatepicker I had the same problem. I solved it using a little trick.

使用这个日期选择器我遇到了同样的问题。我用一个小技巧解决了它。

In the inputs tag I added a new attribute (dp-model):

在输入标签中,我添加了一个新属性 ( dp-model):

<input class="form-control dp" type="text" dp-model="0" />
<input class="form-control dp" type="text" dp-model="1" />
...

And then in the js file I forced the binding in this way:

然后在js文件中我以这种方式强制绑定:

$scope.formData.dp = []; // arrays of yours datepicker models
$('.dp').datepicker().on('changeDate', function(ev){
    $scope.formData.dp[$(ev.target).attr('dp-model')] = $(ev.target).val();
});

回答by user2789261

One of ways around: set the id field to the input, then call document.getElementById('input_name').value to get the value of the input field.

一种解决方法:将 id 字段设置为输入,然后调用 document.getElementById('input_name').value 以获取输入字段的值。

回答by Hossein Aghatabar

im using this, and my code :

我正在使用这个,我的代码:

    this.todayNow = function () {
        var rightNow = new Date();
        return rightNow.toISOString().slice(0,10);
    };
    $scope.selecteddate = this.todayNow();

    $(function() {
        //for displaying datepicker
        $('.date').datepicker({
            format: 'yyyy-mm-dd',
            language:'fa'
        });
        //for getting input value
        $('.date').on("changeDate", function() {
            $scope.selecteddate = $(".date").val();
        });

    });

回答by Frederik Alexander Vygg Larsen

To solve this, I have my HTML looking like this:

为了解决这个问题,我的 HTML 看起来像这样:

<div class='input-group date' id='datetimepicker1'>
<input type='text' ng-model="date.arrival" name="arrival" id="arrival" 
     class="form-control" required />
     <span class="input-group-addon">
         <span class="glyphicon glyphicon-calendar"></span>
     </span>
</div>

My ng-model wouldn't update, so I used this to fix it:

我的 ng-model 不会更新,所以我用它来修复它:

$("#datetimepicker1").on("dp.change", function (e) {
    $scope.date.arrival = $("#arrival").val(); // pure magic
    $('#datetimepicker2').data("DateTimePicker").minDate(e.date); // this line is not relevant for this example
});