在 AngularJS 中集成 jQuery 插件的正确方法 [英] Correct way to integrate jQuery plugins in AngularJS

查看:30
本文介绍了在 AngularJS 中集成 jQuery 插件的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道将 jQuery 插件集成到我的 angular 应用程序中的正确方法是什么.我找到了一些教程和截屏视频,但它们似乎是针对特定插件的.

I was wondering what is the correct way to integrate jQuery plugins into my angular app. I've found several tutorials and screen-casts but they seem catered to a specific plugin.

例如:http://amitgharat.wordpress.com/2013/02/03/an-approach-to-use-jquery-plugins-with-angularjs/http://www.youtube.com/watch?v=8ozyXwLzFYs

我应该像这样创建一个指令 -

Should I create a directive like so -

App.directive('directiveName', function() {
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            $(element).'pluginActivationFunction'(scope.$eval(attrs.directiveName));
        }
    };
}); 

然后在 html 中调用脚本和指令?

And then in the html call the script and the directive?

<div directiveName ></div>
<script type="text/javascript" src="pluginName.js"></script>

先谢谢了

推荐答案

是的,你说得对.如果您使用的是 jQuery 插件,请不要将代码放在控制器中.而是创建一个指令并将您通常拥有的代码放入指令的 link 函数中.

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

您可以查看文档中的几点.你可以在这里找到它们:
常见陷阱

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

正确使用控制器

确保在视图中引用脚本时,最后引用它 - 在引用 angularjs 库、控制器、服务和过滤器之后.

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

在将 AngularJS 与 jQuery 结合使用时,您可以使用 angular.element(element) 而不是使用 $(element)

Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

这篇关于在 AngularJS 中集成 jQuery 插件的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆