【问题标题】:Angular Directives in Contenteditable RegionsContenteditable 区域中的 Angular 指令
【发布时间】:2014-03-13 15:38:45
【问题描述】:

我无法激活插入到我网站上内容可编辑区域的 Angular 指令。如果我使用 scope.$apply(),它表示它已经在运行了。

JS

angular.module('app', [])

.directive('edit', function(){
  return {
    link: function(scope, elm, attr){
      scope.url = "http://www.google.com";
      scope.press = function(){
        document.execCommand('insertHTML', false, '<a ng-href="{{url}}">test</a>');
      };
    }
  };
});

HTML:

<div edit contenteditable="true">Dummy Text</div>
<button ng-click="press()">Press</button>

我希望它编译 url 并在 href 参数中提供有效链接,而不是显示原始代码。

JSBin:http://jsbin.com/moponige/1/edit

【问题讨论】:

    标签: javascript angularjs wysiwyg execcommand


    【解决方案1】:

    您可以在插入 HTML 之前使用 $compile 服务进行编译,

    $compile('<a ng-href="{{url}}">test</a>')(scope)
    

    【讨论】:

    • 出于某种原因,它只输出空括号。 []
    【解决方案2】:

    你有使用 execCommand() 的理由吗? execCommand 期望您传递的 HTML 是一个字符串,这将阻止您获得 Angulars 数据绑定的好处。也就是说,如果您更改范围上的 url 属性,则 DOM 将不会更新。

    我会这样实现它:

    angular.module('app', [])
    
    .directive('edit', function($compile){
      return {
        link: function(scope, elm, attr){
          scope.url = "http://www.google.com";
          scope.press = function(){
            var link = $compile('<a ng-href="{{url}}">test</a>')(scope);
            elm.append(link);
          };
        }
      };
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-07
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      • 2017-10-19
      • 2021-05-15
      相关资源
      最近更新 更多