While you are trying to select an item available in the DOM:
This has never been IMO best practice, because there is no need to create asynchronous behavior for the synchronous dom select function. Due to angular. Element documentation it should look like this:
link: ($scope, $element) => { var domElementFromTemplate = $element.find('myDOMElement'); }
While you are trying to select the item that should be displayed in your directive:
The timeout function should avoid the asynchronous behavior of the DOM rendering, but IMO has much more efficient approaches to solve this problem:
Solution 1)
Another approach is to get the document ready state to make sure the item is available in the DOM, for example:
link: ($scope, $element) => { angular.element(document).ready(() => { var domElementFromTemplate = $element.find('myDOMElement'); }); }
Solution 2)
Another approach is to create another directive for those elements that have been visualized inside the directive, for example. ( myDOMElement ) to avoid DOM injection.
link: ($scope, $element) => {}, template: "<div some-other-child-directive></div>"
Solution 3)
There should be a much better and tidier approach for creating a callback function to ensure that the element is accessible in the DOM. This can be done using ng-init="someCallback()" to run the functionality of your element.
Solution 4)
Yes, using $timeout still works fine until a new $timeout is added to the execution queue and executed after the DOM runs. A wait delay value is not required.
link: ($scope, $element) => { $timeout(() => { var domElementFromTemplate = $element.find('myDOMElement'); } }
source share