【发布时间】:2013-04-07 21:14:23
【问题描述】:
看看这个小提琴: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-控制器 div 不能解决问题,所以请给我一些新的见解)
【问题讨论】:
标签: javascript angularjs angularjs-directive angularjs-scope