1

Runnable CODE: 我的代码

我尝试在双击时将 contenteditable 指令动态添加到 <div> 元素。当我contenteditable在开始时将指令放入 <div> 时,ng-model仍然有效,但是当我将其删除并在ng-dblclick回调中动态添加时,ng-model接缝不再起作用。

有点像这个问题

但我想不出一种角度友好的方式来完成我的工作。我怎样才能解决这个问题?

代码:html

<div ng-app="customControl">
  <form name="myForm" ng-controller="mainControl">

    <!-- Dynamically adding contenteditable directive : doesn't work -->
    <div name="myWidget" ng-model="userContent" ng-click="enableEdit($event)"
      strip-br="true"
      required>Change me!</div>

    <hr>
    <textarea ng-model="userContent"></textarea>

  </form>
</div>

代码:js

angular.module('customControl', []).
controller('mainControl', function($scope) {
    $scope.enableEdit = function(e) {
        $(e.target).attr('contenteditable', '');
    }
})
.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('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);
        }
      }
    };
});
4

0 回答 0