Angular - 当“oninput”与“contenteditable span”时如何“绑定”?

时间:2014-01-08 12:16:26

标签: angularjs onchange contenteditable

<span contenteditable>{{ line.col2 }}</span>

您好,

这段代码擅长初始化,但如果我编辑跨度,就不会发送bing而且我的数组模型永远不会更新......

所以,我试过这个:

<span contenteditable ng-model="line.col2" ng-blur="line.col2=element.text()"></span>

但是“this.innerHTML”不存在。

我该怎么办?

谢谢; - )

3 个答案:

答案 0 :(得分:4)

你可以删除ng-blur,你必须添加这个指令:

<span contenteditable ng-model="myModel"></span>

以下是从documentation获取的指令:

.directive('contenteditable', function() {
  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(ngModel.$viewValue || '');
      };

      // Listen for change events to enable binding
      element.on('blur keyup change', function() {
        scope.$apply(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);
      }
    }
  }
});

答案 1 :(得分:2)

我只会指出您可能的解决方案,然后您需要更好地解析/清理HTML。

<span contenteditable data-ng-blur="bar = $event.target.innerHTML">
    {{bar}}
</span>

// upd。

角点事件,例如点击,模糊,焦点,...... - 使用范围上下文触发,例如this将是当前范围。 使用$event,快乐。

答案 2 :(得分:0)

使用Mirrage和gab帮助解决方案:

<span contenteditable="true" ng-model="ligne.col2">{{ ligne.col2 }}</span>


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

谢谢; - )