如何在被 Angular js 指令替换之前获取原始标记?这个问题已经被问过,但我发布这个问题是因为解决方案对我不起作用,而且我想知道 Angular JS 团队是否可能为此引入了任何新方法。
这是我迄今为止尝试过的:
function $block($compile) {
var html = '<div>new content</div>';
return {
restrict: 'E',
template: function(element, attrs) {
console.log(element); // still getting the new element
return html;
},
link: function(scope, element, attrs) {
console.log(element)
}
};
}
angular.module('directive', [])
.directive('myDirective', $block);
如何获取旧模板,然后将其替换为新模板?
最佳答案
当您 console.log
对象时,浏览器会显示查看该对象时的内容值。记录时还没有。这就是开发者控制台的工作方式。
如果您记录innerHTML
,您会发现它们是不同的:
angular.module('directive', [])
.directive('myDirective', $block);
function $block($compile) {
var html = '<div>new content</div>';
return {
restrict: 'E',
template: function(element, attrs) {
console.log(element[0].innerHTML);
return html;
},
link: function(scope, element, attrs) {
console.log(element[0].innerHTML);
}
};
}
<script src="//unpkg.com/angular/angular.js"></script>
<body ng-app=directive>
<h1>Directive Demo</h1>
<my-directive><div>Old Content</div>
</my-directive>
</body>
关于javascript - 获取被 angularjs 指令替换之前的原始模板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44995247/