首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >绑定监视和$timeout顺序

绑定监视和$timeout顺序
EN

Stack Overflow用户
提问于 2017-08-01 21:40:03
回答 1查看 84关注 0票数 2

我遇到过一个组件的代码,该组件设置了HTML:$scope.htmlContent = $sce.trustAsHtml(content),然后在$timeout中调用一个函数,该函数将使用$element.find('.stuff')...查找该内容中的元素

该代码位于$onInit函数的$scope.$watch中。

我的问题是:我们是否百分之百确定内容的DOM元素将在$element.find之前呈现?有没有更好的方法?

要理解的最小代码:

代码语言:javascript
复制
(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模板:

代码语言:javascript
复制
<pre ng-bind-html="htmlContent"></pre>
EN

回答 1

Stack Overflow用户

发布于 2017-08-01 22:35:48

不确定这个组件实际上应该实现什么……看看这个:

代码语言:javascript
复制
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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45439516

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档