Ways to extract the text from a modifiable div using angularjs

I am currently facing a challenge in extracting content from an editable div. I am having trouble incorporating the Angular template for this task.

The part that is posing a difficulty for me is figuring out how to link model data from the HTML template to the Angular controller.

<div ng-repeat="todo in todos">                 
    <div class="todo.id" ng-model={{ ? }} contenteditable="true">
        <pre>{{ todo.text }}</pre>                          
    </div>
    <button type="button" class="btn btn-link"
        ng-click="editTodo(todo.id)">Edit</button>
</div>

My goal is to pass whatever text is present inside the

<div class="todo.id"></div> 

Due to the fact that my div is within an ng-repeat, I am unable to assign ng-model to a single scope variable.

What should be inserted in place of "ng-model={{ ? }}"? Or is there a workaround for dealing with such a situation?

Your assistance in this matter would be greatly appreciated.

Answer №1

If you want to enable a div to be editable in an Angular application, you will need to create a custom contenteditable directive.

The Angular documentation provides an example of how to do this:

https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#custom-control-example

You can also check out a helpful blog post by Gabo Esquivel on the same topic here:

As illustrated in Gabriel's code snippet, the directive for making a div editable would look like this (comments added for clarity):

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

      // Function to sync model with view when typing 
      function read() {
        ngModel.$setViewValue(element.html());
      }

      //$render is invoked when modelvalue differs from viewvalue
      // Check documentation: https://docs.angularjs.org/api/ng/type/ngModel.NgModelController#
      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      // Trigger read function on blur, keyup, and change events
      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
});

Best of luck!

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

What steps can be taken to avoid children components from re-rendering every time the parent component's state or props change

I am currently working on a tree component structured like this: <UserOrderApproval> <Table> <TableRow> <ComponentList /> </ChildrenProps1> </Parent> </UserOrderApproval> Currently, I am retrie ...

What is the best way to navigate through images only when hovering?

I have a website that showcases a collection of images in a creative mosaic layout. Upon page load, I assign an array of image links to each image div using data attributes. This means that every image in the mosaic has an associated array of image links. ...

When a single object is entered, JSON returns 'undefined', however, it works successfully when using the .map() function

Utilizing Axios to fetch data from DeezerAPI, I initially rendered information using .map() and everything worked smoothly when passing it to a Component. However, when attempting to access a single JSON object, I encountered an 'undefined' error ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

I am unable to access the properties of an undefined element, specifically the 'size' property in Next.js 13

I encountered a problem today while working with Next.js version 13.4 and backend integration. When using searchParams on the server side, I received an error message: "Cannot read properties of undefined (reading 'size')" while destructuring siz ...

Typescript Routing Issue - This call does not match any overloads

Need assistance with redirecting to a sign-up page upon button click. Currently encountering a 'no overload matches this call' error in TypeScript. Have tried researching the issue online, but it's quite broad, and being new to Typescript ma ...

difficulty encountered when using the Angular delete method in conjunction with Express.js

I am trying to send a delete request to my Express server from Angular. remove: function (id) { return $http({ method: 'DELETE', url: '/users/delete/'+ id }) } In my Expr ...

Using Javascript to efficiently reverse geocode multiple locations with Google Maps

I've come across an issue with Google API v3 where batch requests are prohibited without a 2-second delay. As a result, I'm attempting to perform a simple reverse Geocode using just one request at the moment. Currently, my array contains only on ...

I'm looking to establish an SSL connection using Node.js with HTTPS. How can I accomplish

I need assistance on establishing an SSL connection with Node.js using HTTPS. Below is the code I have: const Client = require('node-rest-client').Client; let client = new Client(); const headers = { //"Accept": "application/json", " ...

The challenge with encoding URL in Ajax requests

I am trying to send an encrypted message along with the corresponding key (two-way encryption) to a PHP page for decryption, and then receive the decrypted result in the response. Below is an example of how I am attempting to send the encrypted message us ...

What is the method for transmitting a YAML file in the form of a base64 encoded string?

I am attempting to transmit a yaml file as a base64 string in order for this code to function: const response = await octokit.request('GET /repos/{owner}/{repo}/git/blobs/{file_sha}', { owner: 'DevEx', repo: 'hpdev-content&apos ...

Using the OR condition in the ternary operator within ReactJS

Recently, I have started working on a ReactJS project focusing on menus. In this project, I have successfully implemented logic for the active menu feature. For instance, when a user is on page 2, the corresponding menu item will be highlighted as active. ...

Webpack development server is not recognizing changes to the SCSS files

I successfully compressed and compiled my JavaScript and SCSS files using webpack. The SCSS file is extracted by the 'extract-text-webpack-plugin' into an external CSS file. Below is the code snippet: var path = require('path'); var we ...

The navigator's userAgent property is used to match specific handset identifications

When identifying users on specific devices, I use navigator.userAgent.match to detect certain phones. However, with Android devices, there are various tablets, phones, and set-top boxes to consider. So, my code snippet looks like this: if(navigator.userAg ...

Utilize AngularJS to Dynamically Render ASP.NET MVC PartialView

I am currently working on integrating the Report Viewer for MVC into my Angular application using ASP.NET MVC 5. REPORT: View/Report/Index.cshtml @model JET.Shop.Common.Models.ReportRequestModel @using ReportViewerForMvc; <div> <div class="row" ...

Struggling with getting a dropdown to switch the currently displayed image

I am working on a project that involves displaying a series of 4 images which can be clicked on to reveal a drop-down menu. The selection made in the drop-down menu should change the image to correspond with the choice. Here is the current code I have impl ...

Troubleshooting issues with jQuery `.live()` event not triggering as expected

In a project I am working on, I have implemented complex AJAX functionality to fetch inner page content from a WordPress blog. Due to the dynamic nature of the site, where the DOM is replaced after page load via AJAX, I have opted to use jQuery's .liv ...

How can values be passed to child components in Vue when using component tags for dynamically switching components?

Is there a way to pass values to children components in Vue when using the component tag? It appears that I am unable to pass values to a child component using the component tag without using v-if: <component :is="showNow"></component> ...

Is it possible to selectively hide the remove icon for certain files within the antd Upload component?

Is there a way to specifically hide the remove button in the Antd Upload component for files that meet certain criteria? I am aware of the "showRemoveIcon" prop which disables the remove icon for every file, but is there a way to do this for only one fil ...

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...