2014-03-13 42 views
0

我無法激活插入到我網站上的contenteditable區域的Angular指令。如果我使用scope。$ apply(),它表示它已經在運行。Contenteditable Regions中的角度指令

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> 

我想它來編譯鏈接並給予href參數的有效鏈接,而是顯示了原始代碼。

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

回答

1

你有使用的execCommand的理由()? execCommand期望您傳遞的HTML是一個字符串,這將阻止您獲得Angulars數據綁定的好處。也就是說,如果您更改了作用域上的url-property,則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); 
     }; 
    } 
    }; 
}); 
2

您可以將HTML期運用$編譯服務之前編譯,

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

出於某種原因,只是輸出空的方括號。 [] – James

+0

@詹姆斯請分享代碼。 –