【问题标题】:objects disappear on angular template recompilation对象在角度模板重新编译时消失
【发布时间】: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'));
            });
        }
    };
}]);

尝试点击“克隆我克隆我链接”

请注意,在原始模板中,&lt;span&gt;100&lt;/span&gt; 消失了,因为它是一个对象,而 'String' 字符串仍然会出现。

为什么会这样?此外,如何防止这种情况发生,一旦我点击“克隆我克隆我”链接,原来的&lt;span&gt;100&lt;/span&gt; 就不会消失?

(注意:这是我面临的一个实际问题的简化。在这种情况下,我可以通过将&lt;div ng-controller="Ctrl"&gt;&lt;/div&gt; 包裹在 newTemplate 变量周围来解决这个问题。但是在真正的问题中,我面临添加 ng-控制器 div 不能解决问题,所以请给我一些新的见解)

【问题讨论】:

    标签: javascript angularjs angularjs-directive angularjs-scope


    【解决方案1】:

    我不知道为什么会这样,但你究竟为什么将&lt;span&gt;100&lt;/span&gt; 包裹在$(); 中?如果您删除 $();,单击“克隆我克隆我”后,“100”仍然存在,因此如果不需要代码,您的问题就解决了。

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

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

    【讨论】:

      猜你喜欢
      • 2018-10-02
      • 1970-01-01
      • 2015-11-20
      • 1970-01-01
      • 2016-06-20
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多