1

How to get 2-way binding to work with a span contenteditable="true" instead of an input?

See Plunker

Alex McMillan
  • 17,096
  • 12
  • 55
  • 88

1 Answers1

1

Take a look at this

Working Demo

Hmtl

<body ng-controller="MyCtrl">
  <span contenteditable="true" ng-model="person.name">{{ person.name }}</span>
  <pre ng-bind="person.name"></pre>
</body>

script

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

app.directive('contenteditable', function() {
  return {
    require: 'ngModel',
    link: function(scope, element, attrs, ctrl) {
      // view -> model
      element.bind('blur', function() {
        scope.$apply(function() {
          ctrl.$setViewValue(element.html());
        });
      });

      // model -> view
      ctrl.$render = function() {
        element.html(ctrl.$viewValue);
      };

      // load init value from DOM
     ctrl.$render();
    }
  };
});

app.controller('MyCtrl', function($scope) {
  $scope.person = {name: 'David'};
});
Nidhish Krishnan
  • 20,593
  • 6
  • 63
  • 76
  • That's not going to work because my `s` don't trigger the 'blur' event. See http://plnkr.co/edit/yik6Wwrq2AZWkjxXgjN3?p=preview – Alex McMillan May 20 '14 at 02:48