AngularJS - ng-model fails on contenteditable <span>
ng-bind! Use ng-bind for one-way binding in 'span'.
Please refer here for an example: https://docs.angularjs.org/api/ng/directive/ngBind
So your line would be:<span contenteditable="true" ng-bind="chunk.value"></span>
Hope this help
To make ng-model
work with contenteditable <span>
elements, use a custom directive:
app.directive('contenteditable', ['$sce', function($sce) { return { restrict: 'A', // only activate on element attribute require: '?ngModel', // get a hold of NgModelController link: function(scope, element, attrs, ngModel) { if (!ngModel) return; // do nothing if no ng-model // Specify how UI should be updated ngModel.$render = function() { element.html($sce.getTrustedHtml(ngModel.$viewValue || '')); }; // Listen for change events to enable binding element.on('blur keyup change', function() { scope.$evalAsync(read); }); read(); // initialize // Write data to the model function read() { var html = element.html(); // When we clear the content editable the browser leaves a <br> behind // If strip-br attribute is provided then we strip this out if (attrs.stripBr && html === '<br>') { html = ''; } ngModel.$setViewValue(html); } } };}]);
Usage:
<span contenteditable ng-model="userContent">Change me!</span><p>{{userContent}}</p>
For more infomation, see
- AngularJS
ngModelController
API Reference - Custom Control Example - AngularJS Developer Reference - Creating Custom Directives
The DEMO
The ngModel
won't work as @VtoCorleone pointed out. ngModel docs
The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.
You may have a look at the contenteditable directive.
Otherwise, Potential workaround: have a function that gets called. That function then updates the $scope.chunk.value
within your controller. And it would take care of the other elements' contents as the binding gets updated.
I'm not sure the exact look or functionality that you're going for, but just put it inside of a <textarea>
and style it to look like a <span>
(no border or background, etc). Then when it is in focus
, you add additional styling to know that it can be edited. This way would allow you to use the ng-model
as it is intended to be used. Here is a basic implementation of this approach: Plunker