如何创建使用纳克模型的角度日期选择器指令 [英] how to create an angular datepicker directive that uses ng-model

查看:136
本文介绍了如何创建使用纳克模型的角度日期选择器指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经创建了一个角指令为我的jQuery UI的日期选择器。问题是,当选择了日期的指令不更新输入的纳克的模型。任何想法,为什么?

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 ,您可以将您的指令内使用交互的专用控制器;只需添加要求: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.

这为您提供了第四个参数设置为你的链接功能,这是您在要求控制器要求 - - 在这个情况下,一个实例 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 美丽的东西是它会自动验证和格式化的护理(在特定输入型的情况下),并用之类的东西 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

这篇关于如何创建使用纳克模型的角度日期选择器指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆