绑定监视和$超时顺序

时间:2017-08-01 13:40:03

标签: javascript angularjs

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

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

我的问题是:我们是否100%确定内容的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>

1 个答案:

答案 0 :(得分:0)

不确定这个组件应该实现什么......看看这个:

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

相关问题