$compile function and replace

I had a problem with my code and by playing a little I found a solution but I have no idea why is it working. Here's the thing:

// recompile all audio buttons
angular.element(textAsDom).find('sound-button').each(function(key, element) {
        $compile(angular.element(element))(scope);
});

I got a raw html as a parameter, and inside it I'm looking for directives named "soundButton" and I compile them in order to use their attached scope functions and properties.

However, my first solution was to do it like this:

 // recompile all audio buttons
 angular.element(textAsDom).find('sound-button').each(function(key, element) {
     var compiledSound = $compile(angular.element(element))(scope);

     angular.element(element).replaceWith(compiledSound);
 });

So I first compile the soundButton and link it to the scope and I got a bound element in return. Then I replace the original element with the bound element. But then all angular dirty checking nor event handlers don't work anymore.

As for now my problem is solved, however for the sake of understanding why it didn't work, I'm asking you guys if you can shed some lights about this esoteric stuff.

Thanks

Answers


Sounds like you're approaching this a little weird.

Why not just wire up a directive to sound-button? No need to do .find.

.directive("sound-button", function(){
    return {
        class: 'C',
        replace: true,
        ....
    }
});

Need Your Help

Return cumulated string from this recursive loop

javascript recursion

I'm trying to return a final string which is concatenation of each nested object's string values. I'm not able to get it right.