0

With the markup:

<body ng-app="app" ng-controller="ctrl">
  <h1>Type below in the editable div</h1>
  <h3>Use ng-bind:</3>
  <div class="editable" contenteditable=true obj="obj1" ng-bind="obj1.content"></div>
  <h3>Content:</h3>
  <div>{{obj1.content}}</div>

  <h3>Use interpolation</h3>
  <div class="editable" contenteditable=true obj="obj2">{{obj2.content}}</div>
  <h3>Content:</h3>
  <div>{{obj2.content}}</div>
</body>

And a little bit js:

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

app.controller('ctrl', function($scope) {
  $scope.obj1 = {
    content: ''
  };
  $scope.obj2 = {
    content: ''
  };
});

app.directive('contenteditable', function() {
  return {
    scope: {
      obj: '='
    },
    restrict: 'A',
    link: function(scope, elem) {
        elem.on('keyup', function() {
          var text = elem.text();
            scope.obj.content = text;
            scope.$apply();
        });
     }
  };
});

I was trying to write a contenteditable directive with two way data binding. But strange things happen:

Using ngBind: type something like 'a', the caret jumps back to the first position instead of after 'a';

Using interpolation: type something like 'a', it will become 'aa'.

The live demo: http://jsbin.com/bifabuyu/5/edit

What was happening here and how could I fix it?

Yujun Wu
  • 2,992
  • 11
  • 40
  • 56

1 Answers1

0

I fix your problem with interpolation - just delete {{obj2.content}} from

<div class="editable" contenteditable=true obj="obj2">{{obj2.content}}</div>

and it will work correctly. "Doubling" symbols happens because your directive bind to "obj2", and inside directive you print object "obj2".

strelok2010
  • 1,266
  • 8
  • 12
  • With a initial value, e.x, obj2 = {content: 'hey'}, you'll see it works: http://jsbin.com/bifabuyu/7/edit. So it was not the reason you mentioned – Yujun Wu Jun 23 '14 at 01:22
  • Ok, i'm understand you. In your case, i think you can use ng-model for your directive, see answer http://stackoverflow.com/questions/15269737/why-is-ngmodel-setviewvalue-not-working-from – strelok2010 Jun 23 '14 at 03:31