Establish accuracy on additional inputs through directives when button is clicked within AngularJS

I lack familiarity with AngularJS directives because I typically rely on controllers. Can directives be used to set validity on other inputs? Specifically, I am trying to set validity on a certain input text when a button is clicked, but I can't figure out the code to do so.

Below is the HTML code:

<!DOCTYPE html>
<html ng-app="myApp">

  <head>
    <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>
  </head>

  <body>
    <div class="container">
        <div id="login-container">
            <div class="form-group">
                <span class="glyphicon glyphicon-user"></span>
            </div>
            <form name="loginForm" novalidate>
                <div class="form-group">
                    dasdas -- {{ loginForm.student_code.$error.codeValidity }}
                    <input type="text" class="form-control text-center" name="student_code"  ng-model="studentCode" placeholder="Enter Exam Code" required />
                    <span class="errors" id="error-student-code" ng-if="loginForm.student_code.$error.codeValidity">{{ errors }}</span>
                </div>
            </form>
            <login-button form="loginForm"></login-button>
            <a href="register"><button class="btn btn-primary">Register</button></a>
        </div>
    </div>
  </body>
</html>

Below is the JS Code:

  var app = angular.module("myApp", []);

  app.directive('loginButton', loginButton);

  loginButton.$inject = ["$http", "$window"];

  function loginButton($http, $window){
    return {
        template: '<button type="button" class="btn btn-primary">Take Exam</button>',
        link: function(scope, element, attrs, ctrl){
            element.on('click', function(){
                    form = attrs.form;
                    form.student_code.$setValidity('codeValidity', true);
                    scope.errors = "Code is Invalid";
                });
            }
        }
    }

Here is a live example on plunker: http://plnkr.co/edit/kcdDgZpStQixTpGWqxOp?p=preview

PS.

I understand this could be done with controllers, but I am practicing using directives for a better understanding.

Answer №1

Absolutely, it is indeed possible and you are very close to the correct solution. To achieve this, simply pass the form to the isolated scope and then utilize it in the directive controller. There is no need to manually add an event, as you can make use of ng-click instead. Alternatively, you could utilize $scope.$apply if necessary.

When working with directives, it is possible to use the linking function, but it is not mandatory. In general, it is considered good practice to keep lightweight logic in the controller and handle DOM manipulation within the linking function.

var app = angular.module("myApp", []);

app.directive('loginButton', loginButton);

loginButton.$inject = ["$http", "$window"];

function loginButton($http, $window){
  return {
    template: '<button type="button" class="btn btn-primary" ng-click="click()">Take Exam</button>',
    scope: {
      form: '='
    },
    controller: function($scope){
      $scope.click = function(){
        form = $scope.form;
        form.student_code.$setValidity('codeValidity', false);
      };
      
    }
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.5/angular.js"></script>
<div ng-app="myApp">
    <div class="container">
        <div id="login-container">
            <div class="form-group">
                <span class="glyphicon glyphicon-user"></span>
            </div>
            <form name="loginForm" novalidate>
                <div class="form-group">
                    dasdas -- {{ loginForm.student_code.$error }}<br>
                    <input type="text" class="form-control text-center" name="student_code"  ng-model="studentCode" placeholder="Enter Exam Code" required />
                    <span class="errors" id="error-student-code" ng-if="errors">{{ errors }}</span>
                </div>
            </form>
            <login-button form="loginForm"></login-button>
            <a href="#"><button class="btn btn-primary">Register</button></a>
        </div>
    </div>
</div>

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

Certain unique characters may not be easily searchable within AngularJS

Working on a search bar that pulls projects from an API and displays them. Everything works smoothly, except for when I try to search using the "#" character or any character followed by "#", nothing is returned - not even the "project not found" message ...

"What is the best way to retrieve the value of a div element with jquery

Attempting to retrieve the value of a div using jQuery in Chrome console from this HTML: <div class="col-md-3"> <div class="vou-col" style="cursor: pointer"> <h4>Free Large Bucket</h4> <span class="sku-info">Voucher ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

Nesting Angular Controllers with the Same Controller

Do you think it's a good idea to nest one controller within another in Angular? Here's an example scenario: In my HTML file, the body tag is assigned a controller named "CommonCtrl". Inside this body tag, I'm using includes to load a templ ...

What is the best way to integrate a new unique identifier into an existing MongoDB document using NodeJS?

I am looking to add up a field in a document when I input a new entry that has a replicated unique id. This is the code I have so far: MongoClient.connect(process.env.MONGODB_URI || process.env.DB_CONNECTION, { useUnifiedTopology: true, useNewUrlParser ...

Why is it that I am unable to utilize the post data stored in $var within my PHP document when making an Ajax call?

Hey there! I've got this function that makes an ajax call. But, for some reason, the $value I'm passing isn't defined in my showuser.php file. Can you help me figure out why? function showUser2(value) { var xhr = new XMLHttp ...

Troubleshooting Issue with React Function's Conditional Component Rendering

Currently, I am working on honing my skills in React using Codesandbox. My goal is to conditionally display a functional React component inside a function (within a class-based component) that triggers when a button is clicked. If you'd like to take ...

When working with Nuxt 3, the referrer header may sometimes return as undefined

I am looking to capture the referrer header and store it in a cookie so that I can later use it to populate an axios request during the user's journey on my website. In my app.vue, I currently have the following code snippet: const headers = useReque ...

Enhance Your Website with HTML and JavaScript

Here is the code snippet I am working with: sTAT **javascript** var acc = document.getElementsByClassName("item-wrapper"); var i; for (i = 0; i < acc.length; i++) { acc[i].onclick = function(){ this.classList.toggle("selected"); this.nextElementS ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

employing iframes dynamically to overlay a webpage

I inserted this iframe into a webpage <iframe src='http://redbug.redrocksoftware.com.au:80/Pages/chamara.html' style="position:absolute;z-index:1;" ></iframe> The chamara.html page has a button that, when clicked, should cover the c ...

React: Conceal additional elements once there are over three elements in each section

React: I am trying to create a menu with submenus. My goal is to calculate the number of submenus and if it goes over 3, hide the additional submenus. Below is the code snippet for counting the elements: export default function App() { const ElementRef ...

Rewriting Apache rules for an Angular website that utilizes multiple domains on a single server

I am managing multiple domains that all point to the same server, with some having subdomains. The main site is built using AngularJS. I have a new domain called www.newsite.com that I would like to point to a specific page on the main site, such as http:/ ...

Javascript: A guide on passing an object through multiple nested functions

Hey fellow developers, I'm facing a challenge in my code and seeking advice from the experts out there. I'm attempting to retrieve JSON data from a specific URL, as shown below, and utilize it in a React component outside of the getWeather() fun ...

Max call stack size exceeded error encountered and logged without catching

While attempting to display multiple markers on a Google map within the Ionic framework, I encountered an Uncaught RangeError: Maximum call stack size exceeded error message in the log. The issue seems to be related to the Cordova Google plugin that I am ...

Determining whether a path is absolute or relative: A step-by-step guide

Is there a universal function in node.js that can determine if a given path is absolute or relative? Unlike Windows, which starts with 'C:' or '\', UNIX paths begin with '/'. ...

Can OR be utilized within a find operation?

I am currently developing a social media platform similar to Facebook using Express and MongoDB. One of the features I'm working on is adding friends to user profiles. When a user clicks on a button that says "Send Friend Request" on another user&apos ...

Using JQuery to search for and remove the id number that has been clicked from a specific value

I am in need of assistance with deleting the clicked id number from an input value using jQuery. I am unsure of how to proceed with this task and would appreciate some guidance. To simplify my request, let me explain what I am trying to accomplish. Take ...

How can I effectively utilize executeScript in Selenium and webdriver.io?

I'm currently working on testing a basic form using Selenium, WebDriver.io, and Node.js (with Mocha). Here is a snippet of the code I have: var webdriverio = require('webdriverio'); var expect = require('expect'); describe(' ...

Prompt for confirmation in ASP.NET code-behind with conditions

I've searched around for a solution to this problem. Below is a representation of my pseudocode: bool hasData = ItemHasData(itemid); Confirm = "false"; // hidden variable if (hasData) { //Code to call confirm(message) returns "true" or "false" ...