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>因为它是一个对象而消失了,而“字符串”字符串仍然会出现。

为什么会这样?而且,我怎样才能防止这种情况,一旦我点击“克隆我克隆我”链接,原来的<span>100</span>就不会消失?

(Note: this is a simplification of a real problem that I'm facing. In this case I can solve this by wrapping <div ng-controller="Ctrl"></div> around the newTemplate variable. However in the real problem I'm facing adding the ng-controller div will not solve the problem so please provide me with some new insights)

4

1 回答 1

1

I'm not sure why it's happening, but why exactly do you have <span>100</span> wrapped with $();? "100" remains after clicking "Clone me Clone me" if you remove $();, so if that isn't necessary code your problem is solved.

function Ctrl($scope) {
    $scope.variable = '<span>100</span>';
    $scope.variableB = 'String';
}

http://jsfiddle.net/z9XK3/8/

于 2013-04-08T02:33:17.860 回答