如何将td contenteditable值绑定到ng-model

时间:2016-05-19 01:23:31

标签: javascript html angularjs contenteditable

您好我有以下td元素:

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

无论如何我可以将这个ng-model值从contenteditable td传递给我的控制器?在此先感谢你们

2 个答案:

答案 0 :(得分:4)

绑定到contenteditable不是内置的,但您可以编写一个简单的指令来完成任务。

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

但请注意,在Internet Explorer中,contenteditable无法应用于TABLECOLCOLGROUPTBODY,{{1 }},TDTFOOTTHTHEAD元素直接;内容可编辑的TRSPAN元素需要放在单个表格单元格中(参见http://msdn.microsoft.com/en-us/library/ie/ms533690(v=vs.85).aspx)。

答案 1 :(得分:1)

<强> 1。具有角度满足

使用angular-contenteditable https://github.com/akatov/angular-contenteditable

这可以从满足的元素中获得价值

<div ng-controller="Ctrl">
  <span contenteditable="true"
        ng-model="model"
        strip-br="true"
        strip-tags="true"
        select-non-editable="true">
  </span>
</div>

2.与指令

您可以使用此Directive

该指令最初获得:http://jsfiddle.net/Tentonaxe/V4axn/

angular.module('customControl', []).
  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);
        }
      }
    };
  });
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="customControl">
  <form name="myForm">
   <div contenteditable
        name="myWidget" ng-model="userContent"
        strip-br="true"
        required>Change me!</div>
    <span ng-show="myForm.myWidget.$error.required">Required!</span>
   <hr>
   <textarea ng-model="userContent"></textarea>
  </form>
</div>