使用 jQuery 访问 Angular 指令中的元素

Accessing element in an Angular directive with jQuery

本文关键字:元素 指令 Angular jQuery 访问 使用      更新时间:2023-09-26

我在嵌套指令中有一个表单(在Ionic/Angular项目中)

<ion-content class="scroll-content ionic-scroll  has-header">
  <recipe-form>
    <form id="example-form" action="#" class="ng-pristine ng-valid">
    </form>
  </recipe-form>
<div> 

但是我无法通过jQuery访问它。

我尝试了以下方法,但没有成功:

$(function () {
  #$('#example-form')
  #angular.element(document.querySelector('#example-form'))
  #angular.element.find('#example-form') 
  #angular.element.find('example-form')
  #angular.element(document.querySelector('example-form')) 
}

我还发现了几个SO问题,几乎所有问题都是通过使用语法angular.element(document.querySelector(<element id>))来解决的

但对我来说,它给出了一个空白数组[]

我正在head部分和jQuery之后加载我的js文件。

更新

但是,我在同一个文件中用于按钮单击的以下方法按预期工作

$( document ).ready(function() {
  $(document).on('click', 'a.next', function(e){
    arr = [];
    arr = $('.card.recipe-slider');
    current_card = $(this).closest('.card')[0];
    id = current_card.dataset.id;
    if (validateInput(current_card)){
      $(arr[id]).addClass('active');
      $(current_card).removeClass('active');
    } else {
    }
  })
});

终于,我能够找到我的问题的解决方案。我缺少的要点是,您无法通过指令中的JQuery直接访问form元素。

因此,在@tasseKATT的出色帮助和以下文章中,我能够使其运行

以下是我的最终代码(我正在尝试添加 Jquery 步骤插件)

angular.module('directive.recipeForm',[])
  .directive('recipeForm', function(){
    return {
       restrict: 'E',
       scope: false,
       link: function(scope, element){
         var form = $("#example-form");
         form.children("div").steps({
           headerTag: "h3",
           bodyTag: "section",
           transitionEffect: "slideLeft",
           onStepChanging: function (event, currentIndex, newIndex)
           {
           },
           onFinishing: function (event, currentIndex)
           {
           },
           onFinished: function (event, currentIndex)
           {
           }
         });
       },
       controller: 'newRecipeCtrl',
       templateUrl: 'templates/directives/recipe_form.html'
    }
  });