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

时间:2015-06-12 13:06:26

标签: javascript jquery angularjs

我有一段简单的Angular Code,显示所选的时间。 但所选日期与文本区域不具约束力。 作为替代方案,我使用了正常工作的HTML5 datetime-local输入。 这是jQuery timepicker无法正常工作。

<!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>

2 个答案:

答案 0 :(得分:1)

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

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

app.controller('myCtrl',function($scope) {

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

答案 1 :(得分:0)

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

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

var datePicker = angular.module(&#39; app&#39;,[]);

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 }}