如何使事件的jQuery指令更新NG-模式? [英] How to make a directive update ng-model on jquery on event?

查看:221
本文介绍了如何使事件的jQuery指令更新NG-模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我作出AngularJS指令为一个jQuery日期选择器插件,当日期选择日期改变,应更新NG-模式。

I'm making an AngularJS directive for a jQuery date picker plugin which should update a ng-model when the datepicker date has changed.

下面是code迄今:

angular.module('bootstrap-timepicker', []).directive('timepicker', [
  function() {
    var link;
    link = function(scope, element, attr, ngModel) {
      element.datetimepicker();

      element.on('dp.change', function(event) {
        // update ngModel ?
      });
    };

    return {
      restrict: 'A',
      link: link,
      require: 'ngModel'
    };
  }
]);

我怎样才能在dp.change'事件更新ngModel考虑范围,元素,属性ngModel不可用时,称为事件?

How can I update ngModel in the 'dp.change' event considering that scope, element, attr, ngModel are not available when the event is called?

谢谢!

推荐答案

这是肯定的事情是它已经被添加到任何角度插件不更新 NG-模型角范围内的,我们需要做手工它是jQuery的变化事件。在角jQuery插件应该使用指令总是绑定到DOM,因为指令没有提供过DOM很好的控制。

This is sure thing that any plugin which has been added to angular doesn't update the ng-model of angular scope, we need to manually do it on it's jquery change event. In angular jquery plugin should always binded to DOM using directive, because directive does provide good control over a DOM.

当你在你的问题问 ngModel 元素范围对象不可用 dp.change 的DateTimePicker 里面,我不这么认为此可能是以往任何时候都可能指令链接功能里面,你必须一直做别的事情,或者你错过了这个问题进行讲解。

As you asked in your question that ngModel, element, and scope object are not available inside dp.change event of datetimepicker, I don't think so this could be ever possible inside directive link function, you must have been did something else or you missed to explain in the question.

和您需要添加下面code在 dp.change 活动的日期选择器的udpating NG-模型

And for udpating ng-model of date picker you need add below code on your dp.change event

element.on('dp.change', function(event) {
  //need to run digest cycle for applying bindings
  scope.$apply(function() {
    ngModel.$setViewValue(event.date);
  });
});

在上面code,我们检索到更新的事件对象,然后分配到日期 $ viewValue (在视图中的实际字符串值此后,为了更新) NG-模型,那每一个有什么地方只要这个 NG-模型变量已使用我们需要运行周期的消化利用人工 $适用()的指令链接功能范围。我们跑摘要周期背后的原因是,我们需要推动 NG-模型中该值变量 $ modalValue 在模型中的值,该控件绑定到)。

In above code we retrieved updated date from event object, then assigned to the $viewValue(Actual string value in the view) of ng-model, thereafter in order update that to every where else wherever this ng-model variable has been used we need to run digest cycle manually using $apply() on directive link function scope. The reason behind the we ran the digest cycle is, we need to push that value inside ng-model variable $modalValue(The value in the model, that the control is bound to).

工作Plunkr

让我知道如果你需要更多的东西,我会得到你的细节,谢谢。

Let me know if you required anything more, I'll get you that detail, Thanks.

这篇关于如何使事件的jQuery指令更新NG-模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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