angular controllers and directives using scope

I'm just starting to learn angular and I've run into a problem with the scope in my directive and controller. Take a look at my code:

Controller:

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

    myApp.controller('testCtrl', function ($scope, $http) {

    $scope.doSomething = function() {
       alert("Testing Scope");
   };
});

Directive:

myApp.directive('keyEvents', function($document) {
        return {
            restrict: 'A',
            link: function(scope, element, attrs) {
                $document.on('keypress', function(e) {
                 switch (e.keyCode) {
                    case (49):
                            doSomething();
                            break    

                    default:
                    } 
                }); 
            } 
          }; 
        }); 

HTML:

     <script src= "js/main.js"></script>
     <script src = "js/keyevents.js"></script>

     <body ng-app ="myApp">
        <div ng-controller="testCtrl">
               <div key-events>
               </div>
        </div>  
    </body>

I keep getting this error: Uncaught ReferenceError: doSomething is not defined - how can I access the doSomething function within my directive?

Answer №1

Here is a helpful tip:

performAction();

It is recommended to use

scope.performAction();

When defining a method within a scope of a controller that is inherited in a directive, accessing it through the scope passed as an argument is the correct approach.

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

How to lock a column in place using AngularJS

Attempting to adjust the position of a div in AngularJS (1.5) using the MacGyver library (). The id="reportOption" div remains fixed while the id="reports" div scrolls down. However, there is an issue where the id="reports" div shifts left when scrolling a ...

Numbered keys in JSON

I'm dealing with a JSON object that is passed to a script, and the keys are dynamic which makes it hard for me to access the data. The keys in the JSON object are actually numbers, but no matter how I try to access them, I can't seem to get the ...

How to Enhance Angular ui-router nested views with Resolve?

I have been working on creating a customized version of my Angular 1.4.12 application with nested views. The main purpose behind this customization is to accommodate sections within the app that require a header/content/footer structure, while others do no ...

Nested Tab Generation on the Fly

My goal is to create dynamically nested tabs based on my data set. While I have successfully achieved the parent tabs, I am encountering an issue with the child tabs. Code $(document).ready(function() { var data1 = [["FINANCE"],["SALE"],["SALE3"]]; var da ...

What is the method for obtaining the translate property from a group?

I have multiple SVG groups, each containing a variety of child elements. When a click event occurs on a group, I want to move all groups and their children. I need to access the translate properties of the clicked group so I can adjust the others accordin ...

Troubleshooting issues with sending data from Node.js to MongoDB

I recently started learning nodeJS and I'm facing an issue with sending data from a register form to mongodb. It seems like I made a mistake while using the post method, as I am unable to see the data on postman. const express = require('express& ...

Choose the right Vue.js component for optimal performance

I have a primary element within which there is a secondary element with vue.js 2.0. The issue arises when the secondary element relies on methods from the primary element. Here's an illustration: Vue.component('primary-element', { tem ...

Can you explain the distinction between key and id in a React component?

I have included this code snippet in the parent component. <RefreshSelect isMulti cacheOptions id='a' key = 'a' components={makeAnimated()} options={th ...

When using the jQuery ajax function to validate a form, it is important to note that the $_POST variables

I have an HTML form along with a jQuery function for form validation. After submitting the form values to my PHP files, I notice that the $_POST variable is not being set. What could be causing this issue? <form id="signup" class="dialog-form" action= ...

Enhance the output of an array by incorporating additional text into the values

I'm diving into the world of Apps Script and I have a task at hand - adding some text to each value in an array. However, the code I currently have simply moves those values to another column: function getData() { var sheet1 = SpreadsheetApp.getAct ...

Switch to display only when selected

When I click on the details link, it will show all information. However, what I actually want is for it to toggle only the specific detail that I clicked on. Check out this example fiddle Here is the JavaScript code: $('.listt ul').hide(); $( ...

What is the process of combining two class elements?

In my JavaScript class practice, I'm working on creating two users, each equipped with a weapon. My goal is to have a function within the class that allows the players to attack each other and decrease their health based on the damage of their respect ...

Ensure that the central section of the slider remains illuminated

Looking for help with customizing my "product" slider, lightSlider. I want the middle div to always be highlighted when navigating through the slider. Here's what it looks like currently: Link to screenshot - current. My goal is to achieve this look: ...

Retrieve precise information from JSON for use in React applications

Here is a sample JSON file : [{ "name": "bagette", "price": "0.200" }, { "name": "farine", "price": "1" }, { "name": "tomato", "price": "1.200" }, { "name": "chocola", "price": "4.000" }] I need assistance with extracting data from this J ...

Is there a way to have AngularJS display the date without factoring in time zones?

When retrieving a date from WEBapi, it returns in the format: 2013-01-01T00:00:00 I need it to display as: {{msa.StartDate | date:'yyyy-MM'}} Currently, it shows as: 2012-12 Is there a way to make it ignore time zones and display as: 2013- ...

A guide on converting an HTML tag ID to a PHP string

I am currently working on a project that is giving me some trouble with errors. I have created an HTML file called name.html and a PHP file named result.php. In the HTML file, I included some JavaScript to take us to result.php when we click on the Submit ...

Specialized Directive undermines the functionality of ngRepeat

My initial worry was that I wouldn't be able to replicate the issue, yet, I was able to replicate the problem: jsfiddle The scenario presented is straightforward, but mirrors exactly what I'm facing. In essence, I have a directive that doesn&ap ...

The onChange function in React JS for a Material UI 'number' TextField retains the previous value

In this element, I have an onChange function: <TextField id="rowinput" type="number" defaultValue={this.defaultRows} // defaultRows = 1 inputProps={{ min: "1", max:"5"}} onChange= ...

Can we use the function name as an argument for the setState method?

I have a simple question. In the following code snippet, how is it possible to utilize "prevState" as a function without explicitly coding it as a function? handleAddOne() { this.setState(prevState => { return { counter: prevState.coun ...

Validating an Angular form upon submission using a function name with dots

Does anyone know how to call a 'custom validation directive' by watching the ngModel? In my submit function, the name is dotted.[sllr.save()] <div class="col-sm-10"><input type="text" placeholder="must be numeric" class="form-control" ...