将Jquery转换为angular指令

时间:2016-09-16 04:45:13

标签: javascript angularjs

我是Angular中的新手,但我知道在Jquery工作,我将一些函数转换为Angular指令时遇到问题。有人可以帮助我,这是我的jquery函数

$('.spinner .btn:first-of-type').on('click', function() {
  $(this).closest('.spinner').find('input').val(function(i, v) {
    return parseInt(v, 10) + 1;
  });
});
$('.spinner .btn:last-of-type').on('click', function() {
  $(this).closest('.spinner').find('input').val(function(i, v) {
    return parseInt(v, 10) - 1;
  });
});

2 个答案:

答案 0 :(得分:1)

angular.module("yourmodulname").directive("spinnerDirective", spinnerDirective);

function spinnerDirective(){
   return { //Edit -1
 restrict:"A", //restrict the directive to the attribute
 link: "spinnerDirectiveLink"
    }//Edit-1
}

function spinnerDirectiveLink(scope, element, attribute){


 $('.spinner .btn:first-of-type').on('click', function() {
      $(this).closest('.spinner').find('input').val(function(i, v) {
        return parseInt(v, 10) + 1;
      });
    });
    $('.spinner .btn:last-of-type').on('click', function() {
      $(this).closest('.spinner').find('input').val(function(i, v) {
        return parseInt(v, 10) - 1;
      });
    });

}

HTML

<p spinner-directive></p>

由于你的问题不清楚,这是我们写下指令的一般方法。希望从这里你需要接管转换为你的任务。

答案 1 :(得分:0)

AngularJS附带了自己的jQuery版本,名为jQLite。您可以像这样使用它:

angular.element(<selector>).<operation>

您可以找到更多文档here

注意:您通常不需要使用jQuery。虽然jQuery在Angular中运行良好,但您希望使用更多的Angular样式的开发和DOM操作,使用指令。