AngularJS-文本不与Jquery时间选择器绑定

AngularJS- Text is not binding with Jquery time picker

本文关键字:时间 选择器 绑定 Jquery 文本 AngularJS-      更新时间:2023-09-26

我有一段简单的 Angular 代码,它显示了选定的时间。但所选日期与文本区域不绑定。作为替代方案,我使用了正常工作的HTML5日期时间本地输入。这是jQuery时间选择器不起作用。

<!DOCTYPE html>
<html lang="en" data-framework="angularjs">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
    <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
</head>
<body ng-app="myApp">
    <div ng-controller="myCtrl">
        <input type="text" id="dates" ng-model="tdata">
        <text>{{tdata}}</text>
    </div>
</body>
<script type="text/javascript">
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
    $("#dates").datepicker({
        changeMonth: true,
        changeYear: true
    });
})
</script>
</html>

由于某种原因,当您更改字段的值时,模型不会更新(但是,如果您在字段中键入,那么它将相应地更新)。我能想到的唯一原因是日期选择器的工作方式是它在字段更改时不会发送事件(因此它只是更新字段的值而不会触发任何事件)。

为了解决此问题,您可以将onSelect添加到日期选择器并手动更新 tdata 字段,如下所示......

app.controller('myCtrl',function($scope) {
	$scope.tdata = '';
    
	$("#dates").datepicker({
    	changeMonth: true,
        changeYear: true, 
        onSelect: function(data) {
       		$scope.$apply(function() {
            	$scope.tdata = data;
        	});
    	}
    });
})

尝试一个指令。 看看这个小提琴。

http://jsfiddle.net/louisnovick/upj137e3/

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

datePicker.directive('jqdatepicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
         link: function (scope, element, attrs, ngModelCtrl) {
            element.datepicker({
                dateFormat: 'DD, d  MM, yy',
                onSelect: function (date) {
                    scope.date = date;
                    scope.$apply();
                }
            });
        }
    };
});

您的 HTML 应该是

<input type="text" ng-model="date" jqdatepicker />
<br/>
{{ date }}