AngularJS在不同的指令中有不同的行为element.children()

时间:2019-05-15 11:58:30

标签: angularjs

同事,在指令中尝试获取后代。问题是,如果通过ng-repeat添加了父级的后代,那么element.children()将返回一个空数组。

但是,如果我通过setTimeout ()提出请求,则会达到预期的结果

const app = angular.module('app', []);

app.directive('example', function() {
  return {
    restrict: "C",
    link: function(scope, element, attrs) {
      scope.myExample = ['Example-1', 'Example-2', 'Example-3', 'Example-4', 'Example-5'];
      setTimeout(() => {
        console.log("TCL: element", element.children());
      }, 0)
    }
  }
});

app.directive('rootElement', function() {
  return {
    restrict: "ECA",
    //templateUrl: './pages/page-main/index.html',
    template: '<header>header</header><main>main</main><footer>footer</footer>',
    link: function(scope, element, attr) {
      console.log("rootElement", element.children());


    }
  }
});
<html ng-app="app">
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
<menu class="example">
  <li class="li-example" ng-repeat="example in myExample"
      ng-click="active = !active" ng-class="active ? '' : 'li-example-active'">
     <span>{{example}}</span>
  </li>
</menu>
<hr/>
<root-element></root-element>
<html>

问题-使用setTimeout ()的正确决定还是存在更优雅,更正确的解决方案?

0 个答案:

没有答案