且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-10-21 08:48:04

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

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

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

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

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.

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