AngularJS - ng-model在contentitable <span>上失败

AngularJS - ng-model fails on contenteditable <span>

本文关键字:span 失败 contentitable AngularJS ng-model      更新时间:2023-09-26

我正在学习AngularJS。我遇到了一些我无法解释的事情,也找不到任何解释(或解决方法)。

我有一个简单的AngularJS应用程序,我试图将<span contenteditable="true">绑定到一个值,但它不起作用。如:

<!-- Works as expected -->
<input data-ng-model="chunk.value"></input>
<!-- Shows value, but doesn't bind - changes not reflected in model -->
<span contenteditable="true">{{chunk.value}}</span>
<!-- This is empty -->
<span contenteditable="true" data-ng-model="chunk.value"></span>

我如何使最后一个span使用双向绑定,这样编辑它的值更新块。价值,反之亦然?

ng-bind!在'span'中使用ng-bind进行单向绑定。

请参考这里的例子:https://docs.angularjs.org/api/ng/directive/ngBind

所以你的行应该是:<span contenteditable="true" ng-bind="chunk.value"></span>

希望对您有所帮助

要使ng-model与可满足的<span>元素一起工作,请使用自定义指令:

app.directive('contenteditable', ['$sce', function($sce) {
    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($sce.getTrustedHtml(ngModel.$viewValue || ''));
        };
        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          scope.$evalAsync(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);
        }
      }
    };
}]);

用法:

<span contenteditable ng-model="userContent">Change me!</span>
<p>{{userContent}}</p>

有关详细信息,请参见

    AngularJS ngModelController API参考-自定义控件示例
  • AngularJS开发者参考-创建自定义指令

演示

angular.module('customControl', ['ngSanitize'])
.directive('contenteditable', ['$sce', function($sce) {
    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($sce.getTrustedHtml(ngModel.$viewValue || ''));
        };
        // Listen for change events to enable binding
        element.on('blur keyup change', function() {
          scope.$evalAsync(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);
        }
      }
    };
  }]);
[contenteditable] {
  border: 1px solid black;
  background-color: white;
  min-height: 20px;
}
<script src="//unpkg.com/angular/angular.js"></script>
<script src="//unpkg.com/angular-sanitize/angular-sanitize.js"></script>
<body ng-app="customControl">
 <span contenteditable ng-model="userContent">Change me!</span>
 <hr>
 Content={{userContent}}
</body>

ngModel不会像@VtoCorleone指出的那样工作。ngModel文档

The ngModel directive binds an input,select, textarea (or custom form control) to a property on the scope using NgModelController, which is created and exposed by this directive.

你可以看一下contentitable指令。

否则,可能的解决方法:有一个被调用的函数。然后,该函数更新控制器中的$scope.chunk.value。当绑定更新时,它会处理其他元素的内容。

我不确定你要的确切外观或功能,但只要把它放在<textarea>和样式它看起来像<span>(没有边框或背景等)。然后,当它在focus中时,您添加额外的样式以确保它可以被编辑。这种方式将允许您按照预期使用ng-model。下面是该方法的基本实现:Plunker

ng-model不能与span一起使用。如果你绝对需要,你可以为此编写一个自定义指令。该指令将在contentEditable span上设置keydown,keyup监听器,并更新范围模型(在$apply()内)。这将绑定span内容到模型。

我很快为你创建了一个plunker。看看吧。它将<span>内容同步到范围模型。打开浏览器控制台,以便在键入内容时查看作用域模型的更新。

通过将ng-model-options="{ getterSetter: true }"行为添加到附加了ng-model的元素中。您也可以将ng-model-options="{ getterSetter: true }"添加到<form>中,这将为其中的所有<input>s启用此行为。

示例显示了如何使用ngModelgetter/setter:演示页面