角度动态添加contenteditable指令不起作用?

时间:2013-09-25 12:40:53

标签: angularjs dynamic contenteditable directive

Runnable CODE: my code

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

有点像this Question

但是我无法想到在这里完成我的工作的角度友好的方式。 我该如何解决这个问题?

代码: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);
        }
      }
    };
});

0 个答案:

没有答案