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

Do you have an index.d.ts file available for canonical-json?

I am currently working on creating an index.d.ts file specifically for canonical-json. Below is my attempted code: declare module 'canonical-json' { export function stringify(s: any): string; } I have also experimented with the following sn ...

Troubleshooting: Unable to reset form in Angular

I'm currently working on a project that involves utilizing both bootstrap and angular. While form validation using angular and bootstrap is functional, I've encountered an issue with resetting the form. Although I call $setPristine(), it doesn&ap ...

Unable to deactivate button within component using setState is ineffective

Once the button within the RecipeListItem component is clicked and the handleFavorites function has been triggered, I want the button to become DISABLED. What am I missing in my logic? Because this code isn't functioning as expected... Child compone ...

Commitments when using a function as an argument

While I have a good understanding of how promises function, I often struggle when it comes to passing a function as a parameter: var promise = new Promise(function(resolve, reject) { // Perform asynchronous task ec2.describeInstances(function(err, ...

Getting information from a PHP script using jQuery AJAX with the (webpack based) ZURB Foundation Framework

Currently, I am working on a ZURB Template project that was set up using the foundation client. As part of my work, I have already completed some initial tasks such as enabling ES7 features async/await in Babel7 (ZURB Foundation utilizes gulp as taskrunner ...

Accessing HTML elements that are created dynamically in AngularJS

I am facing an issue where I cannot access a function within a newly created DOM element. Despite my best efforts, I can't seem to figure out what is causing this problem. $scope.createCustomHTMLContent = function(img, evtTime, cmname, evt, cust, ser ...

Finding the number of parameters in an anonymous function while using strict mode can be achieved through which method?

Is it possible to determine the arity of a function, such as the methods.myfunc function, when using apply() to define the scope of this and applying arguments? Following the jQuery plugin pattern, how can this be achieved? (function($, window, document ){ ...

Detect the "@" character through keyUp for the implementation of @mentions feature

I am currently working on implementing an @mention feature using Vue and Vanilla JS, but I am facing issues with targeting the "@" character specifically. Within my template: <trix-editor ref="trix" @keyup="listenForUser" ></trix-editor& ...

Best practice for retrieving the $scope object inside the ng-view directive

Check out my plunk. Incorporating ngRoute into my project. I want to increase a value using ng-click, and upon clicking "Show total", the ng-view template should display the updated value. However, it seems like the scope is not being accessed as expecte ...

Application unable to save data to file with no indication in error logs

Recently, I've been experimenting with the Capture-Website package, which is designed to save website screenshots to a file. Initially, everything was working smoothly until I decided to restart the server. Now, although my code is running without a ...

Using Ajax and jQuery to fetch information from a previous search query

I'm currently utilizing Ajax and jQuery for my chat feature. Some may find it overly complex, but as long as it works, that's all that matters. It's functioning properly on the first friend result, however, not on the others. The issue lies ...

What could be causing the value of response.name to be undefined in this situation?

Despite extensively searching through various StackOverflow threads, none of the suggested solutions seemed to work for my specific scenario. Upon analyzing the response using console.log(response), I received an "Object Object" message. I am puzzled as to ...

The MDL layout spacer is pushing the content to the following line

Here's an interesting approach to Material Design Lite. In this example from the MDL site, notice how the 'mdl-layout-spacer' class positions elements to the right of the containing div, giving a clean layout: Check it out <!-- Event ca ...

Preventing multiple tabs in a form with PHP

I have successfully used JavaScript to prevent a link from being opened in multiple browser tabs every time a user clicks on it. For example, if the destination of my link is Google, it will create a new tab if one does not already exist but refresh the ex ...

I am seeking assistance with incorporating mySQL into my Node.js project with React

Currently, I am working on a web-app utilizing Node.js. The main goal is to retrieve information from my local database in MySQL Workbench. Initially, I decided to focus on building the frontend interface before diving into implementing the functionality s ...

Encountering issues with creating a session in Selenium/webdriver while utilizing Safari 12

Ever since making the update to Safari 12, my automated scripts have been encountering a new error: SessionNotCreatedError: Request body does not contain required parameter 'capabilities'. (Interestingly, this error is exclusive to Safari and d ...

JQuery addClass function not functioning properly when used in conjunction with an AJAX request

I have a website where I've implemented an AJAX pagination system. Additionally, I've included a JQUERY call to add a class to certain list items within my document ready function. $(document).ready(function(){ $(".products ul li:nth-child(3 ...

Is it possible to create a Vue JSX component inside a Single File Component using the <script setup> syntax and then incorporate it into the template of the S

I am impressed by how easily you can create small components within the main component file in React. Is it possible to do something similar with Vue 3 composition API? For example: Component.vue <script setup> const SmallComponent = <div> ...

The issue with session storage persisting even after closing the iframe

Encountering a persistent issue where the sessionStorage remains populated even after closing an iframe and opening another one with the same destination. I assumed that the sessionStorage would be reset and start afresh each time. The iframe is contained ...

Why isn't my custom HTML attribute displaying correctly?

In my current React app project, I have been incorporating custom attributes to HTML tags and React components for End-to-End (E2E) tests using Testcafe. However, I am facing an issue where the additional data-test="burger-menu-btn" attribute is ...