The issue with the custom ng-enter directive is that it fails to transmit the $event data from the

In my current setup, I have implemented a custom directive that detects when the user presses enter and then triggers the same function as ngSubmit in the surrounding form element.

I am facing an issue where I need access to the event from within the controller, but it always shows up as undefined. Has anyone encountered this problem before? What could be causing it? References or explanations are welcome.

Is there a more efficient way to handle this than duplicating the method call twice? (secondary)

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

app.controller('submitCtrl', ['$scope', function($scope) {

  $scope.submitContent = function(event) {
    //I am trying to access this
    console.log(event); //However, it is coming up as undefined.
  }
}]);

app.directive('mvEnter', function() {
  return function(scope, element, attrs) {
    element.bind('keydown keypress', function(event) {
      if (event.which === 13) {
        scope.$apply(function() {
          scope.$eval(attrs.mvEnter);
        });
        event.preventDefault();
      }
    });
  };
});
<!DOCTYPE html>
<html>
<head></head>

<body ng-app='app'>
  <div ng-controller="submitCtrl">
    <textarea mv-enter="submitContent($event);"></textarea>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>

</html>

Answer №1

The $eval method is defined as $scope.$eval(expr, locals). This means that you can utilize the locals object within the $eval function, with the key representing the parameter name ($event).

scope.$eval(attrs.mvEnter, {$event: event});

Check out the Preview here

Answer №2

I made a small adjustment to your code snippet. Take a look and let us know if it worked for you! :)

Here's the breakdown: The $scope.eval function evaluates the expression provided to it. If the expression is a prototype of a function, the method will return the function for execution. So, with the function ready to be executed and the parameter in place, 1 + 1 = 2 hahaha.

I hope this clears things up for you. Feel free to ask if you have any questions!

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

app.controller('submitCtrl', ['$scope', function($scope) {

  $scope.submitContent = function(event) {
    //This is what I am looking for.
    console.log(event); //This is undefined. 
  }
}]);

app.directive('mvEnter', function() {
  return function(scope, element, attrs) {
    element.bind('keydown keypress', function(event) {
      if (event.which === 13) {
        scope.$apply(function() {
          var directiveFunction = scope.$eval(attrs.mvEnter);
          if (angular.isFunction(directiveFunction)) {
            directiveFunction(event);
          }
        });
        event.preventDefault();
      }
    });
  };
});
<!DOCTYPE html>
<html>
<head></head>

<body ng-app='app'>
  <div ng-controller="submitCtrl">
    <textarea mv-enter="submitContent"></textarea>
  </div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
</body>

</html>

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

The npm request was unsuccessful due to a self-signed certificate within the certificate chain causing the failure

I am attempting to launch a React Native project using Expo from this site npm install expo -g expo init AwesomeProject npm start However, when running npm start, I encounter the following error: npm ERR! code SELF_SIGNED_CERT_IN_CHAIN npm ERR! er ...

The jQuery script operates just one time

Recently, I encountered a small issue with my script. It only seems to work once - after that, I have to refresh the page in order to remove a favorite article (which the script is supposed to do). $("a.fav_no").on('click', function () { ...

Is it possible for OrbitControls to maintain rotation based on model origin even while panning?

Let me illustrate my question through an image: Shown here is the top view from the camera, with a grey cube representing a 3D model. The 'X' marks the center of rotation, while the arrow indicates the direction of rotation: Typically, when p ...

Choosing a recently inserted row in jqGrid

After reloading the grid, I am trying to select the newly added row, which is always added at the end. However, it seems impossible to do so after the reload. Is there a reliable way to select the last row after reloading the grid? The current code I have ...

What is the best way to make an HTML table with a static header and a scrollable body?

Is there a way to keep the table header fixed while allowing the table body to scroll in an HTML table? Any advice on how to achieve this would be greatly appreciated. Thanks in advance! ...

Updating content on a webpage via AJAX request without altering the original source code

Within the body of our document, referred to as "form.php," we have the following components: At the head section, there is a JavaScript code block: <script> function showUser(str) { if (str == "") { document.getElementById("txtHint").i ...

Organize a series of <span> elements into rows and columns through the use of CSS, JavaScript, or jQuery

Task: Your challenge is to display a list of span elements in both vertical and horizontal layouts without altering the HTML structure. Input: an unknown number of span elements within a parent span like the example below: <span id="parent"> <sp ...

Exploring the capabilities of the Vuejs EventBus

I've been struggling with this issue for quite some time now, but I just can't seem to get it right! I've looked at various examples online, but none of them seem to solve the problem. Every time I run my test, I keep getting this error: Ex ...

The dynamic table rows are appearing out of order in the DOM

success: function (data, status) { var header = $("#MainDiv"); header.html(null); var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr>"); ...

Sending a multidimensional array from $http within AngularJS

Having trouble passing data from AngularJS to PHP using $http. I can pass $scope.myForm.shopList but not $scope.myForm itself. Angular: goSoft.controller('createShop', function($scope, $http){ $scope.myForm = []; $scope.myForm.shopList = ...

Doubt surrounding the behavior of Node.js when a file is required that does not export anything from a module

My understanding of Node.js' require() function and module.exports is high-level, but I still find some behaviors confusing. Imagine I have two simple one-line files named a.js and b.js. In a.js: require('./b.js'); and in b.js: console. ...

Oops! An issue occurred while creating a pass with the Google Wallet API

I'm currently following the instructions provided at this guide to set up my Google Wallet Pass Generic passes. After generating the payload for my JWT, I encountered an error each time I attempted to test it in Google Wallet. The error message shown ...

Informing ng2-bootstrap's Timepicker of the invalidation

I have integrated ng2-bootstrap's timepicker component into my project. To enhance user experience, I created a custom validation function that is triggered by the ngModelChange() event. However, the timepicker component also comes with its own built- ...

Delay in real-time updates with Axios post in NodeJS and ReactJS

I am facing a peculiar issue with an axios post request. Within an onSubmit function on a react component, I have an axios post that sends a UID and retrieves the count of items associated with that UID in a collection (in this case, items in the basket fo ...

Acquiring radio button input in PHP

I have 2 radio buttons within a form, <label><input type="radio" onclick="this.form.submit()" name="shfaq<?php echo $i; ?>" value="1" id="radiobuttonsondazh_0" <?php if($result['live']==1) echo 'checked'; ?> /> ...

Using regular expressions to extract substrings from URL

I have different URL routes, such as var url = '/product' and '/product/create'. Is there a way to use Regex in order to extract only the route name like 'product'? ...

The wonders of jQuery popup windows

A code was discovered that displays a popup, but it currently relies on transparency (opacity: 0). I would like to modify it to use display: none instead, as the transparent window in the center of my website is causing issues. Here is the JavaScript code ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

What is the best way to position the left sidebar on top of the other components and shift them to the

Currently, I am working on a project to display NBA data fetched from an API. I am aiming to recreate the design showcased here: Dribbble Design My main challenge lies in overlaying the left sidebar onto the main box and shifting the components sligh ...