.html()返回空字符串

时间:2016-02-19 10:56:28

标签: javascript html angularjs angularjs-directive

我有代码:

        htmlObject = '<div status-box></div>';
        template = $compile(htmlObject)($scope);
        $scope.$digest();
        console.log(template);
        var templateAsHtml = template.html();
        console.log(templateAsHtml);

和输出: 从第一个console.log:

  

{0: <div status-box="" class="ng-scope"></div>, length: 1}

从第二个开始:

  

''

似乎我打电话给.html的那一刻它只是没有转换它而且它是空的。

1 个答案:

答案 0 :(得分:4)

当您要求.html()元素时,您将获得innerHTML元素。由于'<div status-box></div>'没有子节点,因此行为正确。如果要返回包含对象本身的HTML,则需要使用outerHTML函数。

var templateAsHtml = template[0].outerHTML;
console.log(templateAsHtml);

参见文档:

注意:[0]用于访问包装器对象内的vanilla JavaScript对象。

相关问题