双向数据绑定到可满足的跨度

时间:2014-05-16 04:36:46

标签: javascript angularjs contenteditable

如何让双向绑定与span contenteditable="true"而不是输入一起使用?

请参阅Plunker

1 个答案:

答案 0 :(得分:1)

看看这个

<强> Working Demo

<强> HTML

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

<强>脚本

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'};
});