在 ng-if 中调用 Javascript [英] Calling Javascript within ng-if
问题描述
我有一些遗留的 jQuery 代码.这是一大块代码,所以我更愿意稍后移植它.要使用它,我调用 $('#legacyId').legacyFunction()
.
不过,这就是交易.
我有一个 ng-if.在那个 ng-if 中,我有 JavaScript 来调用我的遗留函数.
<div id="legacyId">我是一个遗留 div!<script type="text/javascript">$('#legacyId').legacyFunction()
看起来这个 JavaScript 在页面加载时被调用.虽然我在 jQuery 之后加载 angular,但似乎 angular 删除了 ng-if 控制下的部分,因此 #legacyId
上的 jQuery 函数失败.
有什么想法吗?谢谢!
编辑注意:我在 HTML 文档的顶部导入了 jQuery 和扩展 jQuery 的遗留代码.Angular 加载在文档底部.
编辑注 2:我也试过 <div ng-init="$('#legacyId').legacyFunction()"></div>
,但我收到一个错误,Error: [$rootScope:inprog] $apply already in progress.
好的,设法解决了这个问题.
在 HTML 中:
<div 遗留指令>我是一个遗留 div!
在我的应用代码中:
app.directive('legacyDirective' , function() {返回 {链接:函数(范围,元素,属性){$(element).legacyFunction(scope.$eval(attrs.legacyDirective));}}});
因为$(element).legacyFunction(scope.$eval(attrs.legacyDirective));
,看来我也可以给legacyFunction
传参数了;例如<div legacy-directive='{myParameter: true}>
感谢所有回答的人!你让我走上了正轨.
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.
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.
这篇关于在 ng-if 中调用 Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!