我遇到过一个组件的代码,该组件设置了HTML:$scope.htmlContent = $sce.trustAsHtml(content),然后在$timeout中调用一个函数,该函数将使用$element.find('.stuff')...查找该内容中的元素
该代码位于$onInit函数的$scope.$watch中。
我的问题是:我们是否百分之百确定内容的DOM元素将在$element.find之前呈现?有没有更好的方法?
要理解的最小代码:
(function() {
'use strict';
angular.module('mymodule').component('exampleComponent', {
templateUrl: 'path/template.html',
bindings: { content: '<' },
controller: ExampleComponentCtrl
});
function ExampleComponentCtrl($element, $sce, $scope, $timeout) {
this.$onInit = function() {
$scope.$watch(function() {
return $sce.valueOf(self.content);
}, function() {
// irrevelant stuff that creates variable content that contains html code
$scope.htmlContent = $sce.trustAsHtml(content);
// use $timeout to wait for the inner HTML to be injected
// so that we can find `.file-link` elements
$timeout(function() { $element.find('.stuff').each... });
});
};
}
)();HTML模板:
<pre ng-bind-html="htmlContent"></pre>发布于 2017-08-01 22:35:48
不确定这个组件实际上应该实现什么……看看这个:
function ExampleComponentCtrl($element, $scope, $compile) {
var vm = this;
vm.$onInit = function() {
};
vm.$onChanges = function() {
if (vm.content) {
$element.empty();
$element.append($compile(vm.content)($scope)); // if you html does not contain angular, compile is not required
console.log('Found element: ' + $element.find('p')[0].id);
}
};
}http://plnkr.co/edit/3BSwabSDtfuE0q69NnP4?p=preview
https://stackoverflow.com/questions/45439516
复制相似问题