I need help on correctly retrieving the ng-model value in a controller when using it with the contenteditable directive

I've attempted using ng-change, ng-keypress, ng-keyup, and ng-keydown for this issue.

Using ng-change, the ng-model value is being updated in the controller but not reflecting on the front end.

However, with the other three methods, the value displayed is one character less than the original value. For example, if shareText = 'tag3', it only shows 'tag'. How can I ensure that the correct value 'tag3' is displayed?

Answer №1

.directive("contenteditable", function() { return { restrict: "A", require: "ngModel", link: function(scope, element, attrs, ngModel) {

            function read() {
                ngModel.$setViewValue(element.html());
            }

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

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

It is functioning well when implemented in this way. Initially, I used the following in the directive link function: link: function(scope, elm, attr, ngModel) {

            function updateViewValue() {
                ngModel.$setViewValue(this.innerHTML);
            }

            //Alternatively, you can bind it to other events
            elm.on('keyup', updateViewValue);

            scope.$on('$destroy', function() {
                elm.off('keyup', updateViewValue);
            });

            ngModel.$render = function() {
                elm.html(ngModel.$viewValue);
            }

        }

However, when using this inside the directive link function, the changes made with ng-change were not reflecting on the front end.

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

Divide a nested list into individual lists

I am working on a navigation menu with nested lists and I need to split the nested lists using jQuery while keeping the original headings intact. Can anyone help me achieve this? Below is the HTML code: <ul id="bigList"> <li><a href="#"& ...

Customize hover effects in tailwind css with dynamic values

I am trying to customize the text color on hover based on different category names using tailwind CSS. In my configuration, I have assigned a specific color code for each category like this : tailwind.config.js theme: { extend: { } }, co ...

Having trouble toggling journal entries in an HTML journal? The Jquery function might not be working properly

I have been tasked with creating a civil war journal for my 8th grade Social Studies class and I decided to present it as an HTML file featuring the title and date of each journal entry. The goal is to allow users to click on each entry to open it while au ...

Obtaining the source code from a different domain website with the help of jQuery

Is there a way to extract part of the source code from a YouTube page without using server-side programming? I've tried cross-domain AJAX techniques like Yahoo YQL and JsonP. While Yahoo YQL allows me to grab part of the source code, I'm facing ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...

The important role of max and min attributes in bootstrap-ui timepicker

Looking to integrate the timepicker directive from bootstrap-ui in my project. I am having trouble understanding how to utilize the min and max attributes effectively. I attempted to set a time range from 0 to 1440 as follows: <uib-timepicker ng-model ...

What is the best way to display a Base64 image in a server-side DataTable?

This HTML code is designed to load server-side data into a table. The data is retrieved from the controller using AJAX requests. <script type="text/template" id="tablescript"> <td><%=Name%></td> <td><%=PhoneNumber%> ...

Retrieve data from MongoDB using the find() method results in an empty response, however,

While working on a project to practice my MongoDB skills, I encountered an issue with retrieving all the data from MongoDB. Despite receiving a successful 200 response, I was unable to properly extract all the data. Using Express framework for this task, ...

Changes in date format using jQuery datepicker

I am having trouble with the code below. Whenever I attempt to change the date, it switches from 15/5/2012 to 05/15/2012. <script> $(document).ready(function(){ $("#date").datepicker({ }); var myDate = new Date(); var month = myDa ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Unable to utilize Socket.io version 2.0.3

When it comes to developing a video chat app, I decided to utilize socket.io. In order to familiarize myself with this library, I followed various tutorials, but unfortunately, I always encountered the same issue. Every time I attempted to invoke the libr ...

AngularJS ng-table filter for exact matching

I am currently working with the following function: function updateTable(lines) { // console.log("dit is de filter", $scope.filter); lines = lines || []; $scope.tableParams = new NgTableParams({ filter: $scope.filter, ...

AngularJS HTTP service

When using AngularJS to call $http services for fetching JSON data, I consistently encounter the following error: NetworkError: 500 Internal Server Error Below is the snippet of code that I am currently using: app.controller('activeUserController ...

Find out if all attributes of the object are identical

I am trying to create the boolean variable hasMultipleCoverageLines in order to determine whether there are multiple unique values for coverageLineName within the coverageLines items. Is there a more efficient way to write this logic without explicitly c ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...

What could be causing the lack of data for the current user?

I have been attempting to fetch the current user session and display the data in the view, but nothing is appearing. I even checked the database and confirmed an active session with all the necessary information. I attempted logging the user out and starti ...

How can I position 7 images absolutely within a specific div?

I've been working on a website where users can have their avatars displayed using a JS function that loads 7 different images onto the page. These images correspond to different elements such as skin base, hair, eyes, mouth, shirt, shoes, and pants, a ...

Can I obtain a link through the branch_match_id parameter?

Within my application, there exists a hyperlink: hxxp://get.livesoccer.io/IuKk/0CRq5vArLx which leads to the following destination: hxxp://livesoccer.io/news.html?url=http%3A%2F%2Fwww.90min.com%2Fembed%2Fposts%2F4003374-chelsea-star-pedro-loving-life-at-s ...

AngularJS: Transitioning from Expressions to Javascript (Coffeescript)

Looking to convert an expression into JavaScript in order to maintain an object's value in $scope: <dl class = "mortgage-information"> <dt><abbr title = "Loan-to-value Ratio">LTV</abbr></dt> <dd>{{(total_fi ...

Ways to switch text on and off smoothly using transitions

I have created a webpage where text starts off hidden but has a visible heading. When you click on the heading, the text is revealed below. I am putting the final touches and aiming to make the text slide in smoothly. I am using Javascript for toggling ins ...