angular.js icon indicating copy to clipboard operation
angular.js copied to clipboard

Support HTML5 contentEditable attribute

Open vojtajina opened this issue 15 years ago • 78 comments

We should do two-way binding even for other elements than inputs, if there is contentEditable attribute.

vojtajina avatar Aug 20 '11 08:08 vojtajina

a stale piece of code from previous mailing list discussion

<!doctype html>
<html xmlns:ng="http://angularjs.org" xmlns:ngx="http://angularjs.org/extras" ng:controller="MyCtrl">
 <script ng:autobind src="http://code.angularjs.org/angular-0.9.10.js"></script>
  <script>
   function MyCtrl() {
     this.reset = function(){
       this.text = "Hello <b>World</b>!";
     };
     this.reset();
   }

   angular.widget("@ngx:contenteditable", function(expression, template){
     template.attr('contenteditable', 'true');
     return angular.extend(function($updateView, instance) {
       var scope = this,
           lastHtml = instance.html();
       instance.bind('blur keyup paste', function(){
         scope.$set(expression, lastHtml = instance.html());
         $updateView();
       });

       this.$watch(expression, function(value){
         if (value != lastHtml)
           instance.html(value);
       });

     }, {$inject:['$updateView']});
   })
  </script>

 <body ng:controller="MyCtrl">
  <h1>Editor</h1>
  <hr/>
  <div ngx:contenteditable="text" style="border: 1px solid black;"></div>
  [ <a href="" ng:click="reset()">reset</a> ]
  <hr/>
  <textarea rows="10" cols="80" name="text"></textarea>
 </body>
</html>

IgorMinar avatar Aug 20 '11 08:08 IgorMinar

Hey all, so I was unable to get the provided example to work with 0.9.10, let alone with 1.0.0r6.

Any further guidance would be greatly appreciated! (As I'd much rather use contenteditable over a directive that replaces with for inline-edits) :D

brayzn avatar Apr 25 '12 01:04 brayzn

The above code is outdated. Can you update it?

fitzchak avatar Jun 08 '12 10:06 fitzchak

Yes, it would be great if we were able to use contenteditables with AngularJS.

Hengjie avatar Jul 22 '12 03:07 Hengjie

I agree, need 2-way data binding for content editable

nlepisto avatar Aug 07 '12 21:08 nlepisto

I did find a way around this by implementing my own directive (note JS is in CoffeeScript):

angular.module('NameOfYourApp').directive('contenteditable', ->
  return {
    restrict: 'A', 
    require: '?ngModel',
    link: (scope, element, attr, ngModel) ->
      return if not ngModel

      ngModel.$render = ->
        element.html(ngModel.$viewValue)

      element.bind 'blur', ->
        if ngModel.$viewValue isnt $.trim(element.html())
          scope.$apply(read)

      read = ->
        console.log("read()")
        ngModel.$setViewValue($.trim(element.html()))
  }
)

Edit:

And if you don't use CoffeeScript, here's the JS version:

angular.module('NameOfYourApp').directive('contenteditable', function() {
    return {
      restrict: 'A',
      require: '?ngModel',
      link: function(scope, element, attr, ngModel) {
        var read;
        if (!ngModel) {
          return;
        }
        ngModel.$render = function() {
          return element.html(ngModel.$viewValue);
        };
        element.bind('blur', function() {
          if (ngModel.$viewValue !== $.trim(element.html())) {
            return scope.$apply(read);
          }
        });
        return read = function() {
          console.log("read()");
          return ngModel.$setViewValue($.trim(element.html()));
        };
      }
    };
  });

Hengjie avatar Aug 08 '12 02:08 Hengjie

Are you aware of this contentEditable demo? http://docs.angularjs.org/api/ng.directive:ngModel.NgModelController

mhevery avatar Aug 08 '12 03:08 mhevery

@mhevery Is there a reason for not including this directive in Angular?

Wizek avatar Aug 08 '12 06:08 Wizek

I'm aware, though I should have pointed out that mine is slightly different and relies on jQuery's trim function.

Hengjie avatar Aug 08 '12 06:08 Hengjie

@wizek you have to draw the line someplace.

On Tue, Aug 7, 2012 at 11:50 PM, Hengjie [email protected] wrote:

I'm aware, though I should have pointed out that mine is slightly different and relies on jQuery's trim function.

— Reply to this email directly or view it on GitHubhttps://github.com/angular/angular.js/issues/528#issuecomment-7576294.

mhevery avatar Aug 09 '12 17:08 mhevery

@mhevery I wouldn't dispute that for a minute.

Though, may I ask what logic do you follow when deciding where you draw that line?

Wizek avatar Aug 09 '12 19:08 Wizek

@mhevery If Angular included 'input, textfield, etc' on the basis of it being input fields in the HTML4 spec, then by that basis, we should include 'contenteditable' because it's part of the HTML5 spec's input.

Hengjie avatar Aug 10 '12 00:08 Hengjie

I guess we just make a guess. We don't have any official rules. You are free to make your case, or better yet, send us a pull request. I think the demo is bit trivial since I think real content editable is more complicated, but maybe that is all that needs to be done.

mhevery avatar Aug 10 '12 04:08 mhevery

Just dug onto this, and the mud I extracted is quite dirty actually...

If you try the previously mentioned example, you'll notice that with Chrome, any trailing space will result in a final "&nbsp;" displayed at the end of the bound textarea. The same goes if you input two subsequent spaces. The behavior is quite different in Firefox, but the same kind of issues did show up.

This outlines something important: in those contenteditable stuff, you can actually input any HTML code. Try to copy/paste some component of a webpage into that example, and profit.

Being is this situation is a conceptual mess, at least if as me you're just willing to use this as a fancy input box. So I decided to simplify things, and only keep the plain-text information. But if you want the actual binding not to shock the user, you have to remove the formatting from both the $viewValue and the contenteditable element itself.

And here we're inside an immense no man's land of browser specificities. Handling regular typing is almost fine, however when it comes down to copy/paste, there is no simple solution... I mean, neither Chrome nor Firefox have a "paste" event, but do paste the text with formatting, whereas something like KHTML will just refuse to paste anything...

I started something here, that is (almost) stable for Chrome, kind of works for Firefox and is untested for useless and generally incompatible browsers (but that did invent the contenteditable attribute \o/).

However, I actually discourage the use of contenteditable. Indeed, if you try to copy/paste some DOM including a

Owner


Other Repo Issues