如何创建一个使用 ng-model 的角度日期选择器指令 [英] how to create an angular datepicker directive that uses ng-model
问题描述
我为我的 jQuery UI 日期选择器创建了一个角度指令.问题是该指令在选择日期时不会更新输入的 ng-model.知道为什么吗?
I have created an angular directive for my jQuery UI datepicker. The problem is that the directive doesn't update the input's ng-model when a date is selected. Any idea why?
http://jsbin.com/ufoqan/1/edit
推荐答案
AngularJS 实际上提供了一个特殊的控制器来与 ngModel
交互,你可以在指令中使用它;只需将 require: 'ngModel'
添加到您的指令定义中.
AngularJS actually provides a special controller for interacting with ngModel
that you can use inside your directives; just add require: 'ngModel'
to your directive definition.
这为您的 link
函数提供了第四个参数,它是您在 require
中要求的控制器——在本例中,是一个实例 ngModelController
.它有一个名为 $setViewValue
的方法,您可以使用它来设置模型的值:
This gives you a fourth paramter to your link
function, which is the controller you asked for in require
--in this case, an instance of ngModelController
. It has a method called $setViewValue
you can use to set the value of the model:
app.directive('datepicker', function() {
return {
require: 'ngModel',
link: function(scope, el, attr, ngModel) {
$(el).datepicker({
onSelect: function(dateText) {
scope.$apply(function() {
ngModel.$setViewValue(dateText);
});
}
});
}
};
});
ngModelController
的美妙之处在于它会自动处理验证和格式化(在特定输入 type
的情况下)以及与诸如 ngChange 之类的东西的集成
回调;查看这个例子:http://jsbin.com/ufoqan/6/edit
The beautiful thing about ngModelController
is it automatically takes care of validation and formatting (in the case of a specific input type
) and integration with things like ngChange
callbacks; check out this example: http://jsbin.com/ufoqan/6/edit
这篇关于如何创建一个使用 ng-model 的角度日期选择器指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!