Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Here is the html for the date field :

<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-datepicker with angularjs ?

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

like image 605
Deepankar Bajpeyi Avatar asked Oct 11 '13 11:10

Deepankar Bajpeyi


3 Answers

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

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

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

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

like image 161
michaelpoltorak Avatar answered Nov 08 '22 05:11

michaelpoltorak


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.

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

    });

 });
like image 21
Sreekanth Karini Avatar answered Nov 08 '22 06:11

Sreekanth Karini


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
    }
});
like image 2
user5045936 Avatar answered Nov 08 '22 06:11

user5045936