What is the best way to obtain a reference to the parent form element within an AngularJS directive?

Here is the HTML code I am working with:

<form name="my-form">
  <div class="col-sm-4">
    <input type="phone" name="mobileNumber" ng-model="form.mobileNumber" value="0439888999" required>
  </div>
</form>

In addition, I have created a directive in AngularJS:

angular.module('myApp.directives')
    .directive('required', function ($compile) {
        return {
            restrict: 'A',
            require: 'ngModel',
            link: function(scope, element, attr, ngModel) {
                var formName = element.parents('form').attr('name');
                var fieldName = element.attr('name');
            }
     };
});

However, during my unit test, I encountered an error message:

TypeError: Object [object Object] has no method 'parents'
.

I have realized that this error is due to jqLite not supporting the parents method in my version of AngularJS (v1.2.13).

My question now is how can I achieve the same functionality within my directive without using jQuery as a dependency? If jQuery is necessary, how can I properly inject it into my directive and unit test?

Answer №2

If you're looking to verify the form's validity (specifically that a phone number is required), there's a simple code snippet you can use without the need for a custom directive:

  <body ng-controller="MainCtrl">
    <form name="xform">
      <div class="col-sm-4">
        <input test type="phone" name="phone" ng-model="data.phone" required>
      </div>
      <p ng-if="xform.$valid">Valid</p>
      <p ng-if="!xform.$valid">Not valid</p>
    </form>
  </body>

If you do require access to both the model and the form within a custom directive, utilizing the 'require' attribute in the directive will help you achieve that:

var app = angular.module('plunker', []);

app.controller('MainCtrl', function($scope) {
  $scope.data = {};
  $scope.data.phone = '031 584 658';
});

app.directive("test", function(){
  return {
    controller: function($scope) {
      $scope.$watch('xform.$valid', function(newVal, oldVal) {
        console.log('form validity has changed', newVal, oldVal);
      })
    },
    link: function(scope,element,attrs,controllers) {
      var model = controllers[0];
      var form = controllers[1];
      //console.log(model);
      //console.log(form);
      //console.log(form.$valid);
    },
    require: ['ngModel', '^form'],
  }
})

You can view a working example on Plunker.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify the presence of a particular attribute in an HTML tag using Capybara and polling techniques

In my HTML code, the attributes of buttons (such as "AAAAA") will change based on external events. This real-time update is achieved through AJAX pooling. <div class="parent"> <div class="group"><button title="AAAAA"/></div> <di ...

What is the reason for JavaScript consistently returning the initial value as the result?

My current issue involves customizing Joomla article content using a module. I am attempting to hide a div until a user clicks on an input, such as a radio button labeled Test1. Once Test1 is selected, another hidden field within the div should display the ...

Embed programming into an iframe upon its loading

I am looking to enhance the functionality of an iframe by injecting HTML and JavaScript code into it upon loading. The goal is to enable users to navigate through different links within the iframe while they are browsing. Here is what I have attempted so ...

Tips for achieving compatibility between systemjs module loading and .net mvc architecture

Upon finding the ng-book 2, I saw it as a promising resource to delve into Angular 2. Although I am new to module loaders and have minimal experience with npm and node, I find the terminology and assumed knowledge to be quite perplexing. I decided to use ...

Cannot Get jQuery .flip() to Work Automatically Every 2 Seconds

There are 3 words that I want to rotate on their x-axis every 2 seconds (repeating). Using jQuery: $(function () { count = 0; wordsArray = ["Innovation", "Creativity", "Success"]; setInterval(function () { count++; $("#words").text(wordsArray[co ...

Obtaining essential data while facing a redirect situation

I need to extract the og data from a specific URL: https://www.reddit.com/r/DunderMifflin/comments/6x62mz/just_michael_pouring_sugar_into_a_diet_coke/ Currently, I am using open-graph-scraper for this task. However, the issue I'm facing is that it i ...

Terminate the execution of the process.exec function

Currently, I have a function in my code that is responsible for executing a specific process. Here's how it looks: static async runTest() { await process.exec(`start ${currentDir}/forward.py`); } runTest(); Here's the thing – once this Python ...

Looking to integrate the date, month, and year selection tags into the inline format

The Edit User Profile page includes a Birthday field, which is currently displayed vertically. I am looking to change the layout so that the Birthday field appears horizontally. Here is the code I am using: Within visitors/edit.html.erb, <%= simple_f ...

You are unable to access the array beyond the scope of the function

I am encountering an issue with a function I wrote: function gotData(data){ result = data.val() const urls = Object.keys(result) .filter(key => result[key].last_res > 5) .map(key => ({url: 's/price/ ...

Error in JavaScript goes undetected when utilizing asynchronous AJAX

Having recently started working with ajax and javascript, I find myself puzzled by the fact that my error is not getting caught when making an asynchronous ajax call. I did some research on a similar issue in this query (Catch statement does not catch thr ...

Adjust the width of a div based on its height dimension

I have a div called #slideshow that contains images with a 2:1 aspect ratio. To set the height of the image using jQuery, I use the following function: Keep in mind that the Slideshow Div is always 100% wide in relation to the browser window. If the use ...

"Dynamic value changes in bootstrap multiselect dropdowns triggered by selection in another multiselect dropdown

I am trying to enhance the functionality of my multiselect dropdown in Bootstrap by updating the values based on another multiselect selection. Currently, the code works well with one selection, but as soon as I include the class="selectpicker", ...

Effective technique for connecting client-side JavaScript with server-side node.js

I am striving to create a compact website featuring field auto-completion, drawing suggestions from the server's database (utilizing Node.js + MySQL). What approaches can I take to establish client-server communication as the user inputs data into a ...

Implementing the linking of a URL to an HTML hidden button that is dynamically displayed through a Javascript program

I'm currently developing a basic webpage that has a feature allowing users to download the final result as an image file in the last step. To achieve this, I've added a hidden HTML button for downloading the result image and used CSS to set its ...

Using ng-include destroys the styling of the dropdown menu in a bootstrap ul li format

Greetings! I am attempting to replicate the following code snippet that creates a basic dropdown menu using bootstrap: <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="fal ...

What is the best way to assign attributes to all items in an array, excluding the currently selected one?

I need to implement dynamic buttons in my HTML document while a JavaScript class is running and receives a response from the backend. I am using jQuery and vanilla JS, and have included an example below to demonstrate this functionality. The goal is to dis ...

What is the best way to send information from App.js to components?

In my project, I am working with App.js and a functional component called "uploadlist". The goal is to pass a 'custid' value from App.js to the uploadlist component. Here's what I have attempted: app.js: export default class App extends Com ...

"Use AJAX to dynamically update a div element when a button is clicked with a specific value

I have a calendar that is being displayed server side using PHP. My goal now is to allow users to scroll through the months with two buttons (<< / >>) without having to reload the entire page. I have come across many similar questions and examp ...

Guide to automatically closing the calendar once a date has been chosen using owl-date-time

Utilizing Angular Date Time Picker to invoke owl-date-time has been functioning flawlessly. However, one issue I have encountered is that the calendar does not automatically close after selecting a date. Instead, I am required to click outside of the cal ...

Tips for inserting an item into a fresh row

Users are intended to input their question and choose answers. When they click on the "Add Question" button, the question and answer should be added. An issue arises when attempting to add an answer (You can test this in the provided fiddle by clicking he ...