Angularjs。在datepicker中没有更新ng-model [英] Angularjs. ng-model is not being updated in datepicker
本文介绍了Angularjs。在datepicker中没有更新ng-model的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写jquery来使用隐藏的输入区域在文本点击上打开datepicker。这也是多个地方所必需的。
I was trying to write jquery to open datepicker on text click using hidden input area. Also this is required at multiple places.
以下是我的HTML。
<div class="date-format">
<input class="hidden-date-picker" id="hidden-date1" type="hidden" ng-model="date1"/>
<a href="" class="date-picker" id="date1">{{date1 | date: 'dd MMM yyyy a'}}</a>
</div>
<div class="date-format">
<input class="hidden-date-picker" id="hidden-date2" type="hidden" ng-model="date2"/>
<a href="" class="date-picker" id="date2">{{date2 | date: 'dd MMM yyyy a'}}</a>
</div>
以下是javascript -
Following is javascript -
var app = angular.module('index-app', []);
app.controller('index-controller', function($scope) {
$scope.date1 = new Date(2016, 0, 1);
$scope.date2 = new Date();
$('.hidden-date-picker').each(function() {
$(this).datepicker({
changeYear: 'true',
changeMonth: 'true',
startDate: '07/16/1989',
firstDay: 1,
onSelect: function(dateText, inst) {
console.log($scope.$eval($(this).attr('ng-model')));
$scope.$eval($(this).attr('ng-model')).setTime(Date.parse(dateText));
console.log($scope.date1);
}
});
});
$('.date-picker').each(function() {
$(this).click(function (e) {
$('#hidden-' + $(this).attr('id')).datepicker('show')
e.preventDefault();
});
});
});
从控制台输出中可以清楚地看到$ scope.date1在从日历中选择日期时被修改。但这种变化并未在html方面得到反映。
It is clear from the console output that $scope.date1 is being modified on selecting the date from calender. But the change is not being reflected in the html side.
推荐答案
使用指令可以解决ng-model未更新的问题
Using a directive can resolve your problem of ng-model not updated
您的HTML代码
<input class="hidden-date-picker" id="hidden-date1" type="hidden" ng-model="date1" customzdatetime />
在输入代码中添加指令 customzdatetime 。
Add a directive 'customzdatetime' to your input tag.
app.directive('customzdatetime', function () {
return {
restrict: 'A',
require: 'ngModel',
link: function (scope, element, attrs, ngModelCtrl) {
element.datetimepicker({
debug: false,
format: 'DD-MM-YYYY',
maxDate: moment()
}).on('dp.change', function (e) {
ngModelCtrl.$setViewValue(e.date);
scope.$apply();
});
}
};
});
这篇关于Angularjs。在datepicker中没有更新ng-model的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文