Editable HTML element with AngularJS and HTML5 contentEditable attribute
There is a new attribute in HTML5 „contentEditable”. It allows user to edit content of the website elements like „span” or „div”. It might be very useful when you need to make some element editable only in the specific circumstances.
In my TaskRoo project I am using „contentEditable” with AngularJS to make tasks names editable in-place with the double-click.
In this post I will describe how to implement and use AngularJS directive to make HTML element editable in-place. In case you are just looking for solution, you can find complete implementation on plunker:
http://plnkr.co/edit/Yt4bFd9mF9iwZirtWvYg?p=preview
Lets start with HTML:
Nothing fancy here. JQuery and AngularJS libraries are included.
You can spot the „span” tag with „quick-edit”, „ng-model” and „ng-change” attributes. This „span” element we will make editable on double click.
Tags „ng-model” and „ng-change” are basic Angular directives. Ng-model binds „span” tag to a property on the scope. In our case it is bound to „someObj.someValue” which we will later create in JavaScript. Ng-change evaluates the given expression when the user changes the input. In this case, it will call „save” function in JS with „someObj” also taken from JS.
The important bit here is „quick-edit” which is our directive implemented in the JavaScript below.
So, now JavaScript code with explanation in the comments:
That’s it. Just replace „someObj” and „save” function with whatever you need.
Try it working in plunkr.