Avoid activating ng-blur when ng-keydown is triggered in AngularJS

Currently, I am working on a project involving angularJS and I am facing an issue with the execution of ng-blur conflicting with ng-keydown. The problem arises because ng-keydown causes the element to lose focus at a certain point.

The HTML code in question is as follows:

<div contenteditable ng-show="contentEditableSupport" ng-init="oldName = ''" ng-focus="oldName = userGroup.name" ng-model="userGroup.name" strip-br="true"
  ng-blur="editName(userGroup, oldName)" ng-keydown="$event.keyCode === 13 && editName(userGroup, oldName)">{{userGroup.name}}</div>

The custom attribute directive defined for angular is:

angular.module("mainApp").directive('contenteditable', function () {
  return {
      restrict: 'A',
      require: '?ngModel',
      link: function (scope, element, attrs, ngModel) {
          //Code taken from: http://fdietz.github.io/recipes-with-angular-js/common-user-interface-patterns/editing-text-in-place-using-html5-content-editable.html
          function read() {
              ngModel.$setViewValue(element.html());
          }

          ngModel.$render = function () {
              element.html(ngModel.$viewValue || "");
          };

          element.bind("blur keyup change", function () {
              scope.$apply(read);
          });

      }
  };
});

When editing the text within the element, clicking elsewhere triggers the editName method once. However, if the text is edited and "enter" is pressed, the method is called twice. Attempts to use $event.stopPropagation have been unsuccessful in resolving this issue.

Answer №1

The issue you are facing seems to be related to the code that triggers the div to lose focus when the user presses the enter key.

To resolve this, try replacing && editName(...) in your ng-keydown handler with a code snippet that simply causes the control to lose focus. This will ensure that the editName(...) function is only called once by the ng-blur handler when the enter key is pressed, preventing any duplicate calls.

Answer №2

For the 'contentEditable' directive, I made the following adjustments:

          element.bind("blur keydown", function ($event) {
              if ($event.which == 13) {
                  element[0].blur();
              }
          });

I also removed the ng-keydown attribute from the div tag.

Functioning perfectly!

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

Error: Attempting to access a property called 'name' on an undefined variable leads to a TypeError

I am a beginner with MongodB and nodejs. I have successfully implemented the GET method, which returns an empty array. However, when I tried to use POST in Postman for "categories," I encountered this error message: ExpressJS categories route app.js Err ...

Display a webpage in thumbnail form when hovering the mouse over it

I'm in the process of creating a website that contains numerous sub-pages. I want to display all the links on a single page and when a user hovers over a link, I want to show a thumbnail of the corresponding webpage within a tooltip. I've experi ...

How can we limit the files served from an Express static directory to only .js files?

I'm curious to know if it's doable to exclusively serve one specific type of file (based on its extension) from an Express.js static directory. Imagine having the following Static directory: Static FileOne.js FileTwo.less FileThree. ...

The Ajax success callback is failing to update the background-image property after receiving a successful JSON response

I am struggling with setting a background image in wordpress despite receiving a successful ajax response. The image url is being returned successfully in the json response, but I can't seem to set it as a background image. Here is the ajax function ...

Three.js tutorial: Rotating items on each axis individually

Looking to create an interactive 3D item that users can rotate with their mouse freely? I experimented with using three quaternions, one for each axis, and then multiplying them together to determine the final position of the item. // Initializing xQuat, y ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

The transfer of character data from PHP to jQuery is not successful

Working with HTML files In this scenario, the values for the sub combobox are being retrieved through a PHP select query and these values are in character format. I have successfully tested passing integer values. <select name="sub" id="sub"> ...

Tips for handling notifications that have been read and unread in a React application

In my current project using React JS, I am tasked with creating a notifications component that will display account-related activities. The notifications need to be sorted into read and unread categories. My main question is how should I manage the read a ...

Focus on the iPad3 model specifically, excluding the iPad4

I am looking to apply specific CSS that works on iPad 3, but not on iPad 4, or vice versa. Currently, I am able to target both versions by using the following code: @media only screen and (-webkit-min-device-pixel-ratio: 2), only screen and ( m ...

Receiving a "Undefined index" error while passing information to a PHP script via jQuery

I have extensively researched this issue, including reading numerous StackOverflow questions, but I am still unable to find a solution. My problem involves retrieving the 'id' attribute value of an HTML 'a' element with jQuery when the ...

Is there a way for me to verify if I have already made an AJAX data request

I have an image gallery with thumbnails. When a user clicks on a thumbnail, an ajax request is fired. I want to prevent the ajax request from firing again if the user clicks on the same thumbnail and instead use the existing data. $.getJSON(url, function( ...

Enhancing communication between controllers and HTML in AngularJS through scope updates

I have created a new functionality within a telerik grid that tracks the ID of a record. When a row is selected in the grid, the associated service updates the data successfully. However, I am facing an issue where the controller responsible for navigation ...

The calculator is malfunctioning and unable to perform calculations

export default function App() { const [activeKey, setActiveKey] = useState(0); const [storeArr, setStoreArr] = useState([]); function click(selector) { setActiveKey(selector); if (activeKey !== "=") { setStoreArr([...storeArr ...

Sinon.js: How to create a mock for an object initialized with the new keyword

Here is the code that I am working with: var async = require('async'), util = require('util'); var Parse = require('parse/node'); function signup(userInfo, callback) { var username = userInfo.username, email ...

Display only a loading image with a see-through background after submitting the page

After submitting the page, I would like to display a loading image in the middle of the page with a transparent background. The current styling code I have used is as follows: #loading { position: fixed; top: 50%; left: 50%; z-index: 1104; ...

Tips for updating the content of multiple tabs in a container with just one tab in Bootstrap 4.x

I am attempting to create two tab containers, where one is used to describe the content of a set of files and the other is used as a list of download links for the described files. Initially, I tried controlling the two containers using just one tab. I ca ...

Load JavaScripts asynchronously with the function getScripts

Asynchronously loading scripts on my login page: $.when( $.getScript("/Scripts/View/scroll-sneak.js"), $.getScript("/Scripts/kendo/kendo.custom.min.js"), $.Deferred(function (defer ...

The parameter provided should be in the form of a 12-byte string

Hey there, I am facing an issue while trying to delete an entry in my database. Despite attempting JSON.parse on the req.body and rearranging the routes in my routes file, I still can't seem to get it to work. Here is my controller: async function re ...

The React application is unable to communicate with my Express application in a production environment, despite functioning properly during development

Currently, I am attempting to make a basic get request to my express backend located at mywebsite.com/test. The expected response from the server should be {"test": "test"}. While this is working perfectly fine in development on localho ...

Which Angular Lifecycle event should I utilize to trigger a specific action when either two buttons are pressed or when one of the buttons undergoes a change?

In this scenario, we have a total of 6 buttons split into two groups of 3: one on the top and the other on the bottom. let valuesum; let value1; let value2; let ButtonGroup1clicked= false; let buttonGroup2Clicked= false; function click1 (value){ va ...