Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Javascript within ng-if

I have some legacy jQuery code. It's a big chunk of code, so I would prefer to port it a little while later. To use it, I call $('#legacyId').legacyFunction().

Here's the deal, though.

I have an ng-if. And within that ng-if, I have the JavaScript where I call my legacy function.

<div ng-if="status=='yes'">
    <div id="legacyId">
        I am a legacy div!
    </div>
    <script type="text/javascript">
        $('#legacyId').legacyFunction()
    </script>
</div>

It looks like this JavaScript is being called when the page loads. Though I load angular after jQuery, it seems that angular removes the section under control of the ng-if, and therefore the jQuery function on #legacyId fails.

Any ideas? Thanks!


Edit-note: I import jQuery and the legacy code that extends jQuery at the top of my HTML document. Angular is loaded at the bottom of the document.


Edit-note 2: I have also tried <div ng-init="$('#legacyId').legacyFunction()"></div>, but I get an error, Error: [$rootScope:inprog] $apply already in progress.

like image 417
masonjarre Avatar asked Nov 06 '13 22:11

masonjarre


1 Answers

Okay, managed to work this out.

In the HTML:

<div ng-if="status=='yes'">
    <div legacy-directive>
        I am a legacy div!
    </div>
</div>

In my app code:

app.directive('legacyDirective' , function() {
   return {
        link: function(scope, element, attrs) {
            $(element).legacyFunction(scope.$eval(attrs.legacyDirective));
        }
   }
});

Because of the $(element).legacyFunction(scope.$eval(attrs.legacyDirective));, it looks like I can also pass parameters to the legacyFunction; e.g. <div legacy-directive='{myParameter: true}>

Thank you for all who answered! You set me on the right track.

like image 135
masonjarre Avatar answered Sep 24 '22 23:09

masonjarre