Javascript call inside ng-if

I have old jQuery code. This is a big piece of code, so I would prefer it a bit later. To use it, I call $('#legacyId').legacyFunction() .

Here's a deal, however.

I have ng-if. And inside this ng-if, I have JavaScript where I call my deprecated 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. Although I load angular after jQuery, it seems that angular deletes the section running ng-if, and therefore the jQuery function on #legacyId fails.

Any ideas? Thanks!


Edit note . I import jQuery and legacy code that extends jQuery at the top of my HTML document. angular loads at the bottom of the document.


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

+6
source share
1 answer

Well, I managed to solve it.

In HTML:

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

In my application code:

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

Due to $(element).legacyFunction(scope.$eval(attrs.legacyDirective)); it looks like I can pass parameters to legacyFunction ; for example <div legacy-directive='{myParameter: true}>

Thanks to all who responded! You have given me the right path.

+6
source

Source: https://habr.com/ru/post/957545/


All Articles