Executing Directive function from Controller in AngularJS with or without passing parameters

I have been searching extensively on the Internet, but I have not come across any good examples that fit what I'm looking for. This could be because I am new to AngularJS.

What I need is a way to execute some common functions in different situations from either the controller or possibly from various directives, within the directive itself or any other scenario.

Currently, I have two specific situations: 1) I want to add a border to the parent wrapper when an input is focused and remove it when it's blurred. For this, I have written the following functions:

module.directive("myDirective", function(){
    return {        
      restrict: 'A',
      link: function(scope, element, attrs){  
      scope.focusIn = function($event){
        angular.element($event.target).parent().addClass('focus');
      }
      scope.focusOut = function($event){
        angular.element($event.target).parent().removeClass('focus');
      }
});

Now, my question is how can I call these functions from HTML code. For example, if I have the following HTML snippet:

<div class="wrapper">
  <input type="text" my-directive="focusin($event)">
</div>

The above code does not seem to work as expected.

My second question is similar to the first one. I have created a module for password strength where I check the strength of a password. The directive works fine, but I'm struggling with calling this directive's function from one of my controllers.

module.directive("passwordStrength", function(){
    var strongRegex = new RegExp("^(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9])(?=.*[!@#\$%\^&\*])(?=.{8,})");
    var mediumRegex = new RegExp("^(((?=.*[a-z])(?=.*[A-Z]))|((?=.*[a-z])(?=.*[0-9]))|((?=.*[A-Z])(?=.*[0-9])))(?=.{6,})");
    return {        
        restrict: 'A',
        link: function(scope, element, attrs){  
          scope.$watch(attrs.passwordStrength, function(value) {
              if(angular.isDefined(value)){
                  if(strongRegex.test(value)) {
                      scope.strength = 'strong';
                  } else if(mediumRegex.test(value)) {
                      scope.strength = 'medium';
                  } else {
                      scope.strength = 'weak';
                      scope.loginForm.$invalid = true;
                  }
              }
          });
        }
    };
});
<input type="password" placeholder="••••••" class="input-field clearfix password" ng-focus="focusIn($event)" password-strength="focusOut($event)" ng-minlength="8" ng-maxlength="20" name="password" ng-model="loginData.password" required password-strength="loginData.password">

The code above works well for checking password strength, but I would like to trigger this code when the user submits the form using the ng-submit function. Can you please assist me with this?

Plunkr

Answer №1

I believe I have properly understood the queries you have raised;

Regarding point 1) The jQuery element element can be utilized within your link function to capture events taking place on the directive's element:

element.focus(function(event, args) {
    element.parent().addClass('focus');
});

element.blur(function(event, args) {
    element.parent().removeClass('focus');
});

On another note for point 2) I recommend transferring the code from your passwordStrength function into a service and then triggering the function using ng-change on your input component.

Answer №2

1) Check out this dom directive that changes the background color when focused.

.directive('domDirective', function () {
      return {
          restrict: 'A',
          link: function ($scope, element, attrs) {
              element.on('focus', function () {
                  element.css('background-color', 'yellow');
              });
              element.on('blur', function () {
                  element.css('background-color', 'white');
              });
          }
      };
  });

To see it in action, you can visit this Plunker link.

2) Another suggestion is shown in this JSFiddle example

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

In my Node.js application using Express and Passport, I encountered an issue where res.locals.users is functioning properly but the data it

I'm currently working on an application using NodeJS, Express, and Passport. However, I've encountered an issue when trying to display user data in the views. While I am able to retrieve the ObjectID of the user from res.locals.user, accessing s ...

Transferring sizable JavaScript array to the Web API

I've been grappling with this problem for two days... In my JavaScript code, I have a large array comprising 20,000 rows and 41 columns. This data was initially fetched in JavaScript via an ajax call, as shown below: var dataArray = []; var dataRequ ...

Losing the properties of a component when employing the 'as' styled-component attribute on an extended styled-component

I created a CallToAction component as follows: const CallToAction = ({ text = "Default text" }) => ( <S_CallToAction>{text}</S_CallToAction> ) const S_CallToAction = styled.div` // Some styles... ` export default CallToAction ...

Wait until the link is clicked before showing the list element

Is there a way to prevent the display of list element id="two" in the code below until link "#two" has been clicked, removing element id="one"? I am looking for a CSS or JS solution that completely hides the list element rather than just hiding it from vie ...

Modifying modal content disrupts AJAX events

When using jquery-ujs for ajax requests with data-remote="true", I encounter an issue where the first request goes smoothly but subsequent ones break. It seems that when certain events like $('#modal').empty(), $('#modal').tex ...

What exactly is the task of the Angular compiler?

Someone asked me this question today and I couldn't come up with a proper response. When it comes to deploying, Typescript transpiles to JS and then there is tree shaking, "less" (optional), and various optimizations involved. However, is any of this ...

Arrange Vuetify elements in a single page stack

How can I stack two UI components on one page using Vuetify? I've attempted to combine elements within a single bracket, but I keep receiving error messages. When I stack components in separate brackets, only the bottom template appears in the fronten ...

Preventing the repeated execution of a function through the use of process.env or global variables

Deciphering buffers retrieved from my MySQL database in order to obtain a specific string required in multiple parts of my node.js Express module is proving to be a challenge. Although the decrypted string will always remain the same, calling the decrypti ...

Manipulate the timing of css animations using javascript

I am currently working with a progress bar that I need to manipulate using JavaScript. The demo of the progress bar has a smooth animation, but when I try to adjust its width using jQuery $($0).css({'width': '80%'}), the animation disap ...

I'm completely clueless on how to preserve the content of an extension's popup window

I'm struggling to maintain the added contents in my popup window, as they disappear whenever I open a new link or click it away. I've researched content scripts, background scripts, and similar concepts, but I'm unsure how to integrate them ...

Generate a Bootstrap dropdown button using JavaScript

Can you assist me in generating an HTML button using JavaScript with Bootstrap styling and customization? I have successfully created a Bootstrap button: <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id ...

Issue with JQuery click() not triggering on a specific div button

I am attempting to replicate a user's click on a website where I have no control over the code. The specific element I am trying to interact with is a div that functions as a button. <div role="button" class="c-T-S a-b a-b-B a-b-Ma oU v2" aria-dis ...

Utilizing jQuery and CSS for positioning in my debut project: an Etch A Sketch

Hello! I am currently diving into the world of CSS, jQuery, and Javascript, and my first project was creating an etch-a-sketch. So far, I've implemented a few features that are working smoothly. However, I've encountered an issue with the snake f ...

The Colorful World of CSS Backgrounds

I've been searching for hours trying to track down the source of this strange greenish background color. I've combed through every single file and it's starting to drive me insane. Any ideas where this color could be coming from? I highly d ...

Is there a way to transform a fixed parameter into a user input value and display the function's outcome on a different page?

I am in the process of developing a straightforward web application for book searching based on ISBN. The website will feature a text input field for entering an ISBN and a submit button. Essentially, a user can enter an ISBN in the designated box, click s ...

Managing Pop-Ups when browsing on Internet Explorer

I've been working on an Excel VBA macro that automates several tasks on the Medicare website. The macro opens IE, logs in, compares claims, and alerts me to any differences found. However, I've encountered a problem during the log-in step, specif ...

Obscure Promise Structure - Accomplish, Flop, Achieved

I came across the following code block and I'm struggling to understand it. While I have a good grasp on promises in the context of: deferred.then(successCb, errorCb); This code snippet appears to have three callbacks (complete, fail, done>) whic ...

Is there a way to update the parameter name in an array.map function?

I'm a little unsure. Is there a way to dynamically change the marker parameter to marker1, marker2, marker3, and so on depending on the number of elements in the map? Currently, I have this code but I would like each element in the map to have a mark ...

Adjust the position of the footer up or down based on changes in page content height

If I have jQuery at my disposal, how can I achieve the following task? There is a div on the page with dynamic content and no fixed height. The height of this div changes as users type and content appears or disappears accordingly. Although everything is ...

Pass various information to a single client using nodejs

I am facing an issue with my NodeJS application. I need to send different types of data to a single client. The first type of data is real-time information coming from a Java program, and the second type is data retrieved from a database. Currently, I can ...