【问题标题】:angularjs child directive DOM doesn't load fast enoughangularjs 子指令 DOM 加载速度不够快
【发布时间】:2015-01-29 06:59:24
【问题描述】:

您好,我有嵌套指令,其中有一个父指令及其可以被嵌入的子指令。我的问题是当尝试在父链接函数中查找一些 dom 元素时,除非我设置超时,否则它不会返回数组。看起来子渲染/嵌入的速度不够快。那么有没有办法在不使用超时然后调用 find 子元素的情况下解决这个问题?

var app = angular.module('plunker', [])
.run(function($templateCache){
  $templateCache.put('innerPane.html', "<div class='inner-pane' ng-transclude></div>");

  $templateCache.put('slidePaneSelector.html', "<div class='slide-pane'><inner-pane><h2>First Inner Pane</h2></inner-pane><inner-pane><h2>Second Inner Pane</h2></inner-pane></div>");
})
.directive('innerPane', function(){
	return {
		restrict: 'EA',
		transclude: true,
		replace: true,
		templateUrl: 'innerPane.html',
		scope:{},
		link: function(scope,element,attr){

		}
	}
})
.directive('slidePaneSelector', ['$timeout',function($timeout){
	return {
		restrict: 'EA',
		transclude: true,
		replace: true,
		templateUrl: 'slidePaneSelector.html',
		scope:{},
		link: function(scope,element,attr){

			var firstPaneElement = angular.element(element.find('div')[0]);
			var secondPaneElement = angular.element(element.find('div')[1]);
			
			console.log(element.find('div'));		

      $timeout(function(){
          console.log(element.find('div'));
      },100);
		
		}
	}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.22/angular.min.js"></script>
<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <meta charset="utf-8" />
    <title>AngularJS Plunker</title>
    <script>document.write('<base href="' + document.location + '" />');</script>
    <link rel="stylesheet" href="style.css" />
    <script data-require="angular.js@1.2.x" src="https://code.angularjs.org/1.2.28/angular.js" data-semver="1.2.28"></script>
    <script src="app.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <p>Hello {{name}}!</p>
    
    <slide-pane-selector></slide-pane-selector>
  </body>

</html>

Plunker: http://plnkr.co/edit/sS5cSMboSV2mjlRxsgO8?p=preview

【问题讨论】:

  • 超时不是为了时间,而是等待摘要结束。即使您执行 $timeout 0 毫秒,您的查找也会起作用。这是因为 $timeout 在执行之前等待当前摘要结束。话虽如此,我不知道解决方法:(
  • 将其更改为 0 不起作用
  • @user3226075,以下答案是否解决了您的问题?

标签: javascript angularjs angularjs-directive angularjs-compile


【解决方案1】:

您可以使用不带时间组件的$timeout - 它会等到 $digest 循环结束并执行。

我认为,正确的方法是让子指令向父指令“注册”。这是通过require: "^parent" 并通过在父控制器上公开一些register 方法来完成的。

.directive("parent", function(){
  return {
    controller: function($scope, $element){
       this.registerChild = function(childElement){
          // do whatever you need here
       }
    }
  }
}

.directive("child", function(){
  return {
    require: "^parent",
    link: function(scope, element, attrs, parentCtrl){
       parentCtrl.registerChild(element);
    }
  }
}

【讨论】:

    猜你喜欢
    • 2020-07-26
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-16
    • 2012-10-17
    • 1970-01-01
    相关资源
    最近更新 更多