Enabling bidirectional data binding for a contenteditable span element

Is there a way to achieve 2-way binding using a span contenteditable="true" instead of an input field?

Check out the example on Plunker

Answer №1

Check out this demonstration

Live Demo Link

HTML Code Snippet

<body ng-controller="MyCtrl">
  <span contenteditable="true" ng-model="person.name">{{ person.name }}</span>
  <pre ng-bind="person.name"></pre>
</body>

Javascript Code Snippet

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

app.directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      // view -> model
      element.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(element.html());
        });
      });

      // model -> view
      ctrl.$render = function() {
        element.html(ctrl.$viewValue);
      };

      // load initial value from DOM
     ctrl.$render();
    }
  };
});

app.controller('MyCtrl', function($scope) {
  $scope.person = {name: 'David'};
});

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

Navigate to a third-level nested view in Angular-UI-Router without prior knowledge of the second-level nested view

I currently have a few "parent modules", such as: user community In addition, I have "embeddable modules", including: photos videos wiki These embeddable modules can be embedded into the parent modules. Each module does not have cross dependencies. F ...

The status of the removed component takes precedence over the following component

I have a parent component called ShoppingCartDetail. This component renders multiple child components named ShoppingCartProduct. Each child component displays the quantity of the product, buttons to change the quantity, and a button to remove the current p ...

Barrier Preventing My Access to the Page

Currently, I am working on a vue page that includes a navigation-guard. This particular page serves as an 'Update Details' section where I have implemented the use of beforeRouteLeave. The purpose of this setup is to display a warning modal if an ...

Determining the currently active tab in Material UI: A simple guide

I am currently working with the Material UITabs component. I am facing an issue where I need to display details specific to each tab on hover, but my current setup shows the details for all tabs regardless of their active state. Below is how I have impleme ...

Adjust the input and transition the UI slider

Currently, I am facing an issue with two sliders and inputs. When the number in the top slider is changed, the number and slide in the bottom block do not update accordingly. What steps should I take to address this? $(document).ready(function() { var $ ...

Provide Arguments to a Function in Express JS

How's everything going? I'm curious to find out the best way, and if it's possible to send a specific parameter to an express function in NodeJS. I want to pass the string ('admin') or any other string that I choose to the 'R ...

Show a dynamic Swiper carousel upon selecting a thumbnail in an image gallery

I am in the process of creating a thumbnail gallery that includes a slider feature using Swiper. The default setup has the slider hidden, and once an image is clicked, the slider should appear with the selected image. To close the slider and return to the ...

If a condition is present, the checkbox in the list needs to be unchecked

I have a query that relates to my previous question: Checkbox and ng-change. Need to uncheck if condition exists The previous solution worked for a single checkbox, but now I am dealing with a list of checkboxes: <tr ng-repeat="part in partstoorder"& ...

Connecting to another page based on data list selection

I have created a datalist with multiple options and now I want to redirect to another page when one of the options is selected. Here is my initial attempt where I tried to directly add a hyperlink to the option label, but it didn't work as expected. ...

Restore the href attribute following modal closure

Among the buttons in my gridview, there are options to trigger a bootstrap modal, each with different contents: return Html::a('<i class="fa">&#xf06e;</i> ', $key, [ 'title' => 'View det ...

Is there a way for me to have Next.Js automatically download and serve all the external assets on my website?

Currently, I have been putting together a portfolio using headless WordPress and NextJs. To retrieve data from the GraphQl endpoint, I created my own functions which are working perfectly fine. However, my issue lies with media files such as images and pdf ...

Combine several JSON files into a single file

After spending countless hours searching on Google, I finally gathered the courage to ask my question here. I have several json files. localhost/feed01.json localhost/feed02.json localhost/feed03.json All of the json file structures are similar to this ...

Upon completing the XML parsing, the output I receive is coming back as undefined

Similar Question: Why does it keep saying the result property is not defined? I am currently working on parsing XML and encountering an issue where the result variable in my getResult() function is returning a value of undefined. What could be causing ...

When a dropdown list only contains one item, the jQuery change event does not get triggered

I'm currently exploring ways to trigger events when options in a dropdown menu are clicked. I haven't come across any clear explanations on how to achieve this. What I specifically need is to activate the event and utilize the selected value. Usi ...

Creating a sophisticated structure in real-time

Each user's permissions will vary based on their roles. My goal is to create an object structure like this: let permissions = { 'state': { 'tool': ['subTool1', 'subTool2'] } } Here is an example ...

The selected visualization type, gantt with angular-google-chart, is not supported

I'm currently working on a project using AngularJS and attempting to integrate a Google Gantt chart with the help of the angular-google-chart tool, but unfortunately, it's not functioning as expected. Here is the code snippet: JS CODE var app ...

What is the best method to obtain the range of a custom word within my VS Code Extension?

I am trying to develop a feature in my VS Code extension that allows me to retrieve the range of a custom word when I hover over it, provided that the line of text matches a specific pattern. Here is the code snippet I have implemented so far: vscode.langu ...

Using either jQuery's .bind or .change to update the value of a span tag from a calendar when

My booking form allows end users to reserve the date they want. Sometimes, this date can change up until the payment page. If a previously unavailable date becomes available, users are notified and given the option to switch dates. I am looking for a way ...

Exporting data acquired from a MongoDB query using Node.js

I am currently working on exporting the contents of a MongoDB collection by using exports.getAllQuestions = async function (){ MongoClient.connect(url, function(err, db) { if (err) throw err; var dbo = db.db("Time4Trivia"); ...

Switch from using fetch to utilizing axios for making API requests

I used fetch for a 'get' request, but now I want to switch to axios. Can someone please help me convert this code to use axios instead? More details: I am fetching an image and using the blob method to display it to the user. I would like to ach ...