0
檢查出這個小提琴:http://jsfiddle.net/z9XK3/6/對象上的角模板重新編譯消失
<div ng-app="miniapp">
<div ng-controller="Ctrl">
<span ng-bind-html-unsafe="variable"></span>
<span ng-bind-html-unsafe="variableB"></span>
<span class="clone">Clone me Clone me</span>
</div>
</div>
<div class="destination"></div>
var $scope;
var app = angular.module('miniapp', []);
function Ctrl($scope) {
$scope.variable = $('<span>100</span>');
$scope.variableB = 'String';
}
app.directive('clone', ['$compile', function($compile) {
return {
restrict: 'C',
link: function(scope, element, attrs) {
element.bind('click', function(){
var newTemplate = '<span ng-bind-html-unsafe="variable"></span><span ng-bind-html-unsafe="variableB"></span> ';
var compiledOutput = $compile(newTemplate)(scope);
scope.$apply();
compiledOutput.prependTo($('.destination'));
});
}
};
}]);
嘗試點擊「克隆我克隆我的鏈接」
注意,在原始模板中,<span>100</span>
消失,因爲它是一個對象,而'String'字符串仍然會出現。
這是怎麼發生的?此外,如何防止這種情況發生,一旦我點擊「克隆我克隆我」鏈接,原來的<span>100</span>
不會消失? (注意:這是我正面臨的一個真正問題的簡化,在這種情況下,我可以通過將<div ng-controller="Ctrl"></div>
包裝到newTemplate變量來解決這個問題,但是在真正的問題中,我需要添加ng-controller div不會解決問題,所以請給我提供一些新的見解)