Trigger a specific directive instance through a function call when a key is pressed on the

Is it possible to trigger a specific directive instance's function when a global keyboard shortcut is pressed and it has the class "focused" based on ng-class?

Below is some template code:

home.html

<body ng-controller="SampleController">
   <test-question
      ng-repeat="n in [1,2,3]"
      ng-class="{'focused': tracer.focus == n}"
      focusnum = "{{n}}"
      ng-click="tracer.focus = n"
      >
      Test Question {{n}}
    </test-question>
</body>

home.js

angular.module('sampleApp', [])
  .controller("SampleController", function($scope) {
    $scope.tracer = {
        focus: 1
    }
    // Write the logic here to call a function on a specific directive with class focused on keyboard shortcut
  })
  .directive('testQuestion', function() {
    return {
        restrict: 'E',
        link: function(scope, el, attrs) {
          scope.someFunction = function() {};
        }
    }
  });

Link to the working example on Plunker

Answer №1

Consider approaching the problem from a different perspective. Create a directive in your main controller that binds to a specific value. Within this directive, monitor the value and when it changes to true, execute the method within the directive.

In your main controller, you can use a keypress shortcut to change the required value to true based on focus, which is also managed in the main controller. Here's an example:

angular.module('exampleApp', []).controller("ExampleController", function($scope) {
    $scope.directiveFlags = {dir1: false, dir2: false, dir3: false};
    $scope.currentFocus = 'dir1';

    // Set the flag to true for the desired directive on keypress event
    $scope.directiveFlags[$scope.currentFocus] = true; // Will trigger watch
};

sampleApp.directive('customDirective', function() {
    return {
        restrict: 'E',
        scope: {
            watchValue: '@'
        },
        link: function(scope, el, attrs) {
            scope.$watch('watchValue', function() {
                if (scope.watchValue) {
                    scope.someFunction();
                    scope.watchValue = false;
                }
          });
          scope.someFunction = function() {};
        }
    };
});

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

Most effective method for sending information from an HTTP server to a browser client

What is the most effective method for transferring data from the server side to the client when the client is a web browser? The server side is developed in Java, while the client side uses HTML, JavaScript, and AJAX. The communication protocol being uti ...

Iterating through HTML table data using a JQuery for each loop

Currently, I have an HTML table that is structured in the following way: <div class="timecard"> <h3>tommytest</h3> <table class="misc_items timecard_list" border="0" cellpadding="2" cellspacing="0" style="margin:0 auto;"> < ...

Encountered Runtime Error: TypeError - Carousel triggering issue with reading properties of null (specifically 'classList') in Tailwind Elements

Currently, I am encountering the error message: Unhandled Runtime Error TypeError: Cannot read properties of null (reading 'classList') while utilizing the Carousel component. The problem arises when I attempt to populate the carousel with images ...

Is there a way to pull information from a string and organize it into a two-dimensional array?

Utilizing the axios library, I am pulling data from a website. Unfortunately, the data being fetched is in HTML format. The extracted data looks like this: 1 Agartala VEAT 120830Z 23004KT 5000 HZ SCT018 SCT025 34/27 Q1004 NOSIG= 2 Ahmedabad VAAH 120830Z 23 ...

Implementing bi-directional data binding between sibling components in Vue.js

Is it possible to create a dual binding scenario with the typeahead plugin https://github.com/pespantelis/vue-typeahead, where the search terms of two typeaheads are linked? This means that regardless of which search box the user types into, both should ...

Tips for assigning a value in a dropdown menu with AngularJS

Can someone help me with setting the same value in multiple drop-down lists using angular.js? Below is an explanation of my code. <table class="table table-bordered table-striped table-hover" id="dataTable"> <tr> <td width="100" align ...

Opt for utilizing a global npm package over repeatedly installing it

Is there a way to utilize the globally installed package without needing to reinstall it every time we run npm i? Here's the scenario I have: I've set up a docker image with a specific package already installed (installation command in the Docker ...

formik does not support using the "new Date" function as an initial value

I have been trying to set the initial value of a date in my component like this, but when it renders I am encountering an error. const formik = useFormik ({ initialValues: { dob: new Date () } }) During this process, I'm facing the follow ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

List the attributes that have different values

One of the functions I currently have incorporates lodash to compare two objects and determine if they are identical. private checkForChanges(): boolean { if (_.isEqual(this.definitionDetails, this.originalDetails) === true) { return false; ...

Tips for integrating map coordinates into a URL

In my React app, there is a Leaflet map that I want to update the URL dynamically with position information (latitude, longitude, and zoom) whenever the map is moved. For example: app.com/lat,lng,z/myroutes Furthermore, default values for lat, lng, z sho ...

Opting for fetch over jQuery's ajax for making successful GET requests to an API

Recently, I found myself in a situation where I needed to convert a function that uses a remote API from returning a callback to returning a Promise. This change presented an opportunity for me to also switch from using $.ajax to fetch, since fetch already ...

What is the best method to handle errors when retrieving JSON data and updating it using fetch()?

I need to figure out a way for the setMessage not to appear when encountering a PUT ERROR 404 not found in the updateTemplate function. I attempted using catch(err) but was unsuccessful. Here is the complete code snippet: My unique version of the code... ...

The query for Node.js using mysql is not defined

Recently, I've been working with Node.js and attempting to incorporate mysql in conjunction with nodejs. Specifically, I have written a query trying to retrieve numbers from a table: select numbers from TABLE, but the end result shows up as: "undef ...

Is there a way to showcase the string message from BadRequest(message) utilizing Ajax?

I am currently working on implementing an API Controller. public ActionResult<Campaigns> AddCampaign([Bind("Name, Venue, AssignedTo, StartedOn, CompletedOn")] Campaigns campaigns) { try { if (ModelState.IsVal ...

Creating a PDF document with multiple pages using a PHP loop, integrating with AJAX, and utilizing the m

Looking for assistance with a plugin development project involving PDF generation using AJAX. The challenge lies in generating multiple PDFs for each user within a loop. The goal is to create PDFs with multiple pages for individual users. If that's n ...

I'm experiencing an issue with loading the GeoJSON file on my localhost

I included this vector into my local host code, but the JSON file does not seem to load. geojson_layer = new OpenLayers.Layer.Vector("features", { projection: epsg4326, strategies: [new OpenLayers.Strategy.Fixed()], pro ...

What could be the reason behind the failure of $cookieStore.get() in retrieving the value?

I am currently testing the cookie functionality in AngularJS. I'm encountering an issue where the console is returning 'undefined' when trying to retrieve a saved value from the cookie using $cookieStore.put(). It seems to work fine when set ...

Create a directive for AngularJS that utilizes SVG elements without using the deprecated

I rely heavily on directives for creating and manipulating intricate SVGs. With the deprecation of "replace" in directive factories starting from version 1.3.??, I am facing a dilemma on how to construct a valid SVG without utilizing replace: true in my di ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...