0

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?

j.wittwer
  • 9,497
  • 3
  • 30
  • 32
undefinedman
  • 620
  • 1
  • 11
  • 25

1 Answers1

1

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.

Jay Shukla
  • 5,794
  • 8
  • 33
  • 63