Вопрос

I'm unable to activate Angular directives that are inserted into a contenteditable region on my site. If I use scope.$apply(), it says it was already running.

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>

I want it to compile the url and give a valid link in the href parameter, instead it shows the raw code.

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

Это было полезно?

Решение 2

Do you have a reason for using execCommand()? execCommand expects the HTML you pass to be a string, which will prevent you from getting the benefit of Angulars data-binding. That is, if you change the url-property on the scope, the DOM won't get updated.

I'd implement it like this instead:

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

Другие советы

You can compile before inserting HTML useing $compile service,

$compile('<a ng-href="{{url}}">test</a>')(scope)
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top