vellattukudy vellattukudy - 6 months ago 26
Javascript Question

How to bind an td contenteditable value to ng-model

Hi i have the following td element:

<td ng-model="name" contenteditable='true'></td>


Is there anyway I can pass this ng-model value from the contenteditable td to my controller? Thanks in advance guys

Answer

Binding to contenteditable isn't built in, but you can write a simple directive that will accomplish the task.

app.directive("contenteditable", function() {
  return {
    restrict: "A",
    require: "ngModel",
    link: function(scope, element, attrs, ngModel) {

      function read() {
        ngModel.$setViewValue(element.html());
      }

      ngModel.$render = function() {
        element.html(ngModel.$viewValue || "");
      };

      element.bind("blur keyup change", function() {
        scope.$apply(read);
      });
    }
  };
});

Take note, however, that in Internet Explorer, contenteditable cannot be applied to the TABLE, COL, COLGROUP, TBODY, TD, TFOOT, TH, THEAD, or TR elements directly; a content editable SPAN or DIV element would need to be placed inside the individual table cells (See http://msdn.microsoft.com/en-us/library/ie/ms533690(v=vs.85).aspx).

Comments