等待所有子组件都绑定到DOM | AngularJS

时间:2018-07-22 09:20:26

标签: javascript angularjs dom

我在AngularJS 1.7.2中有一个组件,其中带有少量嵌套组件:

| parent
| - child
| - - child1
| - - child2

在父组件中,我想获取 child1 组件,该模板的模板以<div id="child-1">开头并添加事件侦听器。例如(父组件):

$ctrl.$onInit = () => {
  $element.find('#child-1').addEventListener()
};

问题是 $ element.find('#child-1')未定义,因为此组件(child1)尚未链接到DOM。

>

有什么方法可以等待所有子元素都绑定到DOM吗?

谢谢!

2 个答案:

答案 0 :(得分:0)

您可以从以下代码中使用:

controller('paret',function($scope,Service,){
  Service.then(function(Data){
        $scope.data = Data;
  })
})
.controller('childOne',function($scope){
  $scope.$watch('Data', function() {
       console.log($scope.data);
  });
})

答案 1 :(得分:0)

一种选择是使用$ timeout服务将事件添加到调用堆栈的最后,调用堆栈将在呈现组件之后调用该事件。

尝试一下

$ctrl.$onInit = () => {
  $timeout(function(){ 
    $element.find('#child-1').addEventListener(); }
    , 0);
};