简体   繁体   中英

Datepicker does not update ng-model

So, I've put together a very simple datepicker:

HTML:

<div ng-controller="DatepickerCtrl">

<div style="display:inline-block; min-height:290px;">
    <datepicker min-date="minDate" show-weeks="false" class="well well-lg" ng-model="dt">    </datepicker>
</div>

<p>Date: {{dt}}.</p>

JavaScript:

angular.module('services', ['ui.bootstrap']);
angular.module('services').controller('DatepickerCtrl', function ($scope) {
$scope.toggleMin = function() {
    $scope.minDate = $scope.minDate ? null : new Date();
};
$scope.toggleMin();
});

The datepicker loads correctly but the ng-model is not updated and the paragraph at the end of the markup shows a blank value for "dt".

I saw a few similar issues posted on GitHub ( https://github.com/angular-ui/bootstrap/issues/808 , https://github.com/angular-ui/bootstrap/issues/784 ) but none of the solutions there solved the issue.

Any thoughts?

I am always suspicious when I see ng-model referencing something without a dot (.) in the name. If your controller code has $scope.dt change it to:

$scope.form = {};
$scope.form.dt = null;

Then in your html change references from "dt" to "form.dt". As Misko says if you have a ng-model without a dot you are doing it wrong.

Best of luck,

Jerry

I ran into a similar problem before! This stuff always drives me crazy. In Angular, the way data-binding works and how views are updated is not too well documented. But one thing I learned is that anytime you try to update the view using something that is not supported by Angular, you want to $watch the variable whose value is changing so that each time the value does change, Angular will call $digest() which runs through the changes and updates the view.

You can read more about $watch here: https://docs.angularjs.org/api/ng/type/ $rootScope.Scope

So back to your case:

Try $watch() on the variable that will change (alternatively, you can use $watchGroup for multiple changing variables). For instance:

$scope.$watch('minDate'), function(newVal, oldVal, scope){
    if(newVal != oldVal){
        scope.minDate = newVal;
    }
}

Hope this helps!

尝试使用该代码,我总是使用 [(ngModel)]:

    <datepicker min-date="minDate" show-weeks="false" class="well well-lg" [(ngModel)]="dt">    </datepicker>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM