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?