在NG-如果调用的JavascriptNG、Javascript

2023-09-13 05:11:05 作者:我会笑。咆哮。

我有一些遗留的jQuery code。这是code的一大块​​,所以一小会儿后,我会preFER将它移植。要使用它,我称之为 $('#legacyId')。legacyFunction()

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().

这里的交易,虽然。

我有一个NG-IF。而这在NG-如果,我有JavaScript的在那里我把我的legacy功能。

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>

它看起来像这样的JavaScript被调用的页面加载时。虽然我的jQuery后装入角,似乎角去除下的NG-如果控制的部分,因此对jQuery函数 #legacyId 失败。

任何想法?谢谢!

编辑 - 注意:我导入jQuery和,在我的HTML文档的顶部延伸的jQuery传统code。角被装载在文档的底部。

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.

编辑 - 注2 :我也试过&LT; D​​IV NG-的init =$('#legacyId')legacyFunction()&GT;&LT; / DIV&GT; ,但我得到一个错误,错误:[$ rootScope:inprog] $已经在进行中适用

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.

推荐答案

好了,总算把工作了这一点。

Okay, managed to work this out.

在HTML:

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

在我的应用程序code:

In my app code:

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

由于的 $(元素).legacyFunction($范围的eval(attrs.legacyDirective)); ,它看起来像我还可以传递参数给 legacyFunction ;例如&LT; D​​IV传统的指令性='{myParameter:真正}&GT;

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.