查看此视频: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>
来解决这个问题。然而,在实际问题中,我所面临的添加ng-controllerdiv将无法解决问题,所以请为我提供一些新的见解)
我不知道为什么会发生这种情况,但为什么你有<span>100</span>
与$();
包装?如果你删除了$();
,点击"克隆我克隆我"后"100"仍然存在,所以如果这不是必要的代码,你的问题就解决了。
function Ctrl($scope) {
$scope.variable = '<span>100</span>';
$scope.variableB = 'String';
}
http://jsfiddle.net/z9XK3/8/