Search code examples
angularjstimeoutelementangular-directive

Directive does not see elements in AngularJS


I am having troubles to understand why my directive does not seem to work properly. Here's the quick overview of the problem:

I load the HTML using Ajax that contains Angular elements. The Ajax response is $compiled, so those elements works, but the problem is that I have to timeout it with 0 seconds.

<div my-directive button="bar">
    <button id="foo">Foo</button>
</div>
<button id="bar">Hi!</button>

and the js:

app.directive('myDirective', function() {
return {
    link: function(scope, element, attrs) {
        var foo = element.find('button');
        var bar = $(attrs.button);
    }
};
});

The above foo-bar elemenets will not be found until I surround them with setTimeout(..., 0);

Can someone tell me if there's a better approach to get access to them without having setTimeout?


Solution

  • What you are doing is the right way to achieve this but you should use $timeout.

    app.directive('myDirective', function($timeout) {
    return {
        link: function(scope, element, attrs) {
            $timeout(function() {
               var foo = element.find('button');
               var bar = $(attrs.button);
            },0);
        }
    };
    });
    

    It's just changing priority of execution code in javascript.