Calling Javascript within ng-if

丶灬走出姿态 提交于 2019-12-12 10:45:32

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/19824121/calling-javascript-within-ng-if

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!