angularJS editable input field with click-to-exit functionality

One issue I encountered involved an editable text field directive in Angular, which is structured like this:

myApp.directive('editable', function () {
    return {
        restrict: 'E',
        scope: {
            model: '=',
            placeholder: '@'
        },
        replace: false,
        template: '<span>' +
        '<input type="text" class="form-control" placeholder="Press enter to submit changes" ng-model="model" style="width: 100%; font-size: 18px" ng-show="edit" ng-enter="edit=false"></input>' +
        '<span ng-show="!edit">{{model || placeholder}} <i class="fa fa-pencil" style="font-size:14px;"></i></span>' +
        '</span>',
        link: function (scope, element, attrs) {
            scope.edit = false;
            element.bind('click', function () {
                scope.$apply(scope.edit = true);
                element.find('input').focus();
            });
        }
    };
});

myApp.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind('keypress', function (e) {
            if (e.charCode === 13 || e.keyCode === 13) {
                scope.$apply(attrs.ngEnter);
            }
        });
    };
});

The current implementation relies on the ng-enter directive triggering actions upon pressing the enter key.

My goal now is for the functionality to also be triggered when clicking away from the element. I attempted to include additional code for this purpose, however, it did not yield the desired outcome:

myApp.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind('keypress', function (e) {
            if (e.charCode === 13 || e.keyCode === 13) {
                scope.$apply(attrs.ngEnter);
            }
        });
        element.bind('keypress', function (m) {
            if (m.charCode === 1 || m.keyCode === 1) {
                scope.$apply(attrs.ngEnter);
            }
          });
    };
});

I'm currently seeking insights on why this modification did not work as intended.

Answer №1

If you're looking to capture when a user leaves a field, you should use the blur event instead of second keypress bind. Here's an example of how you can achieve this:

element.bind('blur', function (e) {
    scope.$apply(attrs.ngEnter);
});

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 ajax request functions smoothly on the OS X Paw app and cURL, but does not work properly when coded in Javascript / jQuery

Currently delving into the world of ajax requests, I've been utilizing the Paw app to troubleshoot one. Surprisingly, the request functions flawlessly within Paw itself and even the cURL code generated by Paw works like a charm. However, the JavaScrip ...

Tips for effectively overlaying one container on top of another in a responsive manner

There are a pair of containers. The main container functions as the parent, while the child container acts as a tag to categorize the content. The objective is to position the tag container at the top right corner of the main content container, slightly of ...

In what way can the result of the code displayed be considered as truthful?

this.someService.findDevices() .subscribe((segments) => { this.segments = Array.from(segments.segments); this.packs.forEach((pack) => { pack.segments = Array.from(segments.segments); pack. ...

Submitting form by clicking a link on the page

To submit a POST request with "amount=1" without displaying it in the URL, I need the site to send this request when any link on the site is clicked. This JavaScript code achieves that with a GET request: window.onload = function () { document.body.oncli ...

Ways to add a string to an array as a labeled object in javascript?

Is there a way to manipulate the array in imageCollection to achieve the format of the array in carouselPhotos as shown below? export default class HomeScreen extends Component { state = { imageCollection: [ { name: "P ...

Implementing Angular2 with conditional loading

One of the requirements for my project is to redirect users to the login page before loading the Angular2 application, without actually loading it. The project is built using angular2-quicksart. After minifying the Angular2 js file: <script> va ...

Retrieving data response post upload with JQuery and an HTML5 Uploader

After uploading an image and receiving a successful post response with the id of the inserted image, how can I insert this response as a data-id attribute within a a tag? Where in the function does this process occur? Here is the function: function img_ ...

Refresh a div element automatically with information from a different webpage using jQuery

I've been attempting to automatically reload a page and fetch new data every 10 seconds, or even less. However, the codes I've tried so far have not been successful. Here is my current approach... // script // <script> $(document).rea ...

Changing the string "2012-04-10T15:57:51.013" into a Date object using JavaScript

Is there a way to transform the format "2012-04-10T15:57:51.013" into a Date javascript object using either Jquery or plain Javascript? ...

Node.js - updating the value of a exported integer variable

In my file A.js, I have defined a module-level variable called activeCount and exported it using module.exports. In another file named testA.js, I am attempting to access and modify the value of activeCount. Despite my efforts, changes made to activeCount ...

The use of callbacks in Model.findById() is now deprecated due to a MongooseError

Hello there! I've run into an issue and could use some assistance, thank you in advance! Running MONGOOSE VERSION: "mongoose": "^7.0.3" Error Message: MongooseError: Model.findById() no longer accepts a callback at Function.findB ...

Using the AngularJS directive with $http to handle JSON responses

Following the steps mentioned here I am using Ajax to retrieve server data which is in Json format containing markup with a directive. I am attempting to use $compile to trigger this directive, but so far, I have been unsuccessful. Below is the controlle ...

Unselect all checkboxes except for the one that was clicked

In a project, I have 3 checkboxes that are interconnected and when one is clicked or checked, I want the others to be cleared while keeping the clicked checkbox checked. This behavior is similar to radio buttons but I cannot use radio buttons due to client ...

What is the best way to implement jQuery after new elements have been added to the DOM?

I'm currently working on a Sentence Generator project. The program is designed to take a list of words and retrieve sentences from sentence.yourdictionary.com based on those words. The first sentence fetched from the website is displayed using the cod ...

Prevent the function from being triggered repeatedly while scrolling

When a user scrolls to the bottom of the page, the following code is meant to load the next page. However, there are instances where it repeats itself due to rapid scrolling or while the AJAX content is still loading. Is there a way to prevent this code f ...

The Javascript Image() function fails to load or render

I am currently in the process of developing a basic Sprite class for implementation in a canvas game. However, I am encountering an issue where the image specified during the creation of a new instance of the class does not trigger the onload or onerror ev ...

The Angular downgradeComponent feature is experiencing difficulties in its creation process

I recently set up a hybrid application using AngularJS and Angular 5 with downgradeModule. I successfully converted a small component from AngularJS to Angular, but unfortunately, it is not being created. I've added console.logs in different parts of ...

Displaying a date and time beautifully in jQuery/JavaScript by providing the day of the week along with the specific time

Does anyone know of a Javascript library, preferably a jQuery plugin, that can take datetimes in any standard format (such as ISO 8601) and convert them into user-friendly strings like: Wednesday, 5:00pm Tomorrow, 9:00am Saturday, 11:00pm I'm not c ...

Ways to guarantee the protection of APIs that are accessible to both front-end applications and other servers

In the process of creating a website, I am faced with the challenge of enabling the front-end page to communicate with the server using AJAX for data retrieval and posting. The same APIs offered by the server are also utilized by private apps within the ...

My React application is being loaded by Express regardless of the route I access. What could be causing this issue?

I'm struggling to access the json data located at /species because express always seems to load the react app regardless of the route I use. Can someone help me identify the issue? Here is an excerpt from my server.js file: const app = require(' ...