将jQuery插件转换为指令角 [英] Convert jquery plugin into directive angular

查看:120
本文介绍了将jQuery插件转换为指令角的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将jQuery插件转换为指令。以下是图书馆: Github

I'm trying to convert jQuery plugin into directive. Here is the library: Github.

在文档中有一个选项:

$(document).ready(function() {
        $("#datepicker").datepicker();
        $("#datepickerbtn").click(function(event) {
            event.preventDefault();
            $("#datepicker").focus();
        })
    });

我创建的指令:

app.directive('dateP', function(){
    return{
        restrict:'A',
        require:'ngModel',
        link:function(scope, element, attr, ngModel){
            $(element).datepicker(scope.$eval(attr.dateP));
            console.log('hey');
            ngModel.$setViewValue(scope);
        }
    }
}); 

但它不工作,任何帮助都会感激。

but it's not working , any help would be appreciate it .

Plunker

我已阅读: https://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/

推荐答案

基本上你写了 ng-mode 而不是 ng-model 和指令你应该定义日期选择器选项而不是范围$ eval(attr.dateP)这是完全错误的。在 datepicker 中,您需要在 json 格式像这里我们提到的选项为 {format:'dd / mm / yyyy'})

Basically you written ng-mode instead of ng-model and directive you should define date-picker options not the scope.$eval(attr.dateP) which is totally wrong. Inside datepicker you need to provide their options in json format like here we mentioned option as { format: 'dd/mm/yyyy' })

HTML

<input date-p id="datepicker1" class="input-small" type="text" ng-model="dt">

指令

app.directive('dateP', function() {
  return {
    restrict: 'A',
    require: 'ngModel',
    link: function(scope, element, attr, ngModel) {
      element.datepicker({
        format: 'dd/mm/yyyy'
      });
    }
  }
});

更新

为了显示 datepicker 在按钮上,您需要在控制器中添加以下方法。

For show datepicker on button click you need to do add below method inside your controller.

控制器

$scope.showDatepicker =  function(){
  angular.element('#datepicker1btn').datepicker('show');
};

Working Plunkr

谢谢。

这篇关于将jQuery插件转换为指令角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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