将已编译的dom转换为angularjs中的html代码
发布时间:2020-12-14 16:36:27 所属栏目:资源 来源:网络整理
导读:我写了一个有postLink的指令,我编译了一些html代码并用 angularjs渲染它.但问题是我无法从生成的DOM中获取html代码. 我的代码是: app.directive("showResultAsText",['$compile',function ($compile) { return { restrict: 'A',compile: function compile(t
我写了一个有postLink的指令,我编译了一些html代码并用
angularjs渲染它.但问题是我无法从生成的DOM中获取html代码.
我的代码是: app.directive("showResultAsText",['$compile',function ($compile) { return { restrict: 'A',compile: function compile(tElement,tAttrs,transclude) { console.log('compile'); var watchModal = tAttrs["showResultAsText"]; var elem = jQuery(tElement); var oriHtml = elem.html(); elem.empty(); return { post: function postLink(scope,iElement,iAttrs,controller) { scope.$watch(function () { return scope.$eval(watchModal); },function (newVal) { if (newVal) { var s = $compile(angular.element(oriHtml))(scope); console.log(s); console.log(s[0]); console.log(s[0].outerHTML); console.log($('<div>').append(s[0]).html()); iElement.text(s[0].outerHTML); } }); } } } } } 您可以看到我使用console.log来打印s的值.在控制台中,它输出: 你可以看到console.log(s)和console.log(s [0])有很多信息,但是当我使用outerHTML时,内部按钮都缺失了. 我也尝试使用jquery:jQuery(s [0]).html(),但同样的事情发生了. 将s转换为HTML代码的正确方法是什么? 解决方法
如果你能提供一个plunkr / jsFiddle示例会更容易,但我想我知道什么是错的.你被控制台愚弄了 – 当你执行console.log(s)时它不会立即被记录(它是异步的) – 控制台获得对dom元素s [0]的引用,并且到时它是准备打印角度是通过它的渲染完成的.另一方面,s [0] .outerHTML和s.html()是同步的,因此您可以获得预角度渲染结果.要解决这个问题,你可以做一个简单的setTimeout:
setTimeout(function(){ console.log(s[0].outerHTML); }); Angular现在应该有时间在回调之前进行渲染(我认为你不需要延迟,但我可能错了).您还可以使用angular $timeout-service,它使用$scope包装回调函数.$apply – 请参阅http://docs.angularjs.org/api/ng.$timeout (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |