简体   繁体   中英

How to access DOM element of directive from another directive?

I'm trying to access DOM element in Directive's link function. The element is located in the view of another directive. Here is the code:

first directive

    (function () {
        'use strict';
        angular.module("testAPP",[])


        .directive('firstDirective', function(){
            var directive = {
                 restrict: 'E',
                 templateUrl: 'firstDirective.html'
                }
                return directive;
        })
  })();

second directive

(function () {
      'use strict';
       angular.module("testAPP",[])
        .directive('anotherDirective', function(){
             var directive = {
                restrict: 'E',
                templateUrl: 'anotherDirective.html',
                link: function($scope){
                  //element from another directive's view

                  var height = document.getElementByClassName("sky")[0].offsetHeight;
                }
             };
             return directive;

           });
     })();

There is a console error saying that height variable is undefined. I tried timeout function and that worked for me, but i think it's not a good solution:

setTimeout(function(){
  var height = document.getElementByClassName("sky")[0].offsetHeight;
  console.log(height);
});

I also tried " require ", but it caused an error that the directive can't be found (i think this might be because that directives are located in separate directories)

So, could you tell me the reason why require does not work, and suggest me better solution than timeout

首先,这似乎不是一个好主意,而且会被认为是“不好的做法”-您还必须更改指令的优先级,以使其能够按需要的顺序进行编译进行编译,以确保第二个指令尝试访问元素时第一个指令已准备就绪。

I think, your content directive load before your 2nd directive, Add ng-if on your content directive may fix the issue

    angular.module("testAPP",[])
                .directive('secondDirective', function(){
       var directive = {
       restrict: 'E',
       templateUrl: 'secondDirective.html',
       link: function($scope){
           $scope.scondDirctiveLoaded = true;
       }
     };
     return directive;
    });

<second-directive></second-directive>
<div ng-if="scondDirctiveLoaded">
    <content-directive  ng-if="scondDirctiveLoaded" ></content-directive>
</div>

This error happens as the directive is instantiated before the DOM is actually ready. $timeout works as it delays the grabbing of the element until Angulars next tick cycle - while this feels like an anti-pattern it seems to be an acceptable solution to the problem.

There is already an answer to a question similar to this.

How can I run a directive after the dom has finished rendering?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM