如何在AngularJs中调用第三方插件库

在AngularJs中我们会不可避免的使用第三方库,例如jquery插件库。我们不能散乱的在AngularJS中引入这些库,例如在controller中。那么应该怎么在Angular中使用第三方库呢?

如何使用?

很简单,给插件写一个directive。

在这里,我会使用一个简单的jquery插件Toolbar.js 的DEMO。

这是我们如何在jquery中创建一个tooltip的:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- Click this to see a toolbar -->  
  2. <div id="format-toolbar" class="settings-button">  
  3.     <img src="http://paulkinzett.github.com/toolbar/img/icon-cog-small.png">  
  4. </div>  
  5.    
  6. <!-- Our tooltip style toolbar -->  
  7. <div id="format-toolbar-options">  
  8.     <a href="#"><i class="icon-align-left"></i></a>  
  9.     <a href="#"><i class="icon-align-center"></i></a>  
  10.     <a href="#"><i class="icon-align-right"></i></a>  
  11. </div>  

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <!-- Typical jQuery plugin invocation -->  
  2. $('#format-toolbar').toolbar({  
  3.     content: '#format-toolbar-options',   
  4.     position: 'left'  
  5. });  

在Angular中使用

在这里我们自定义一个元素属性'toolbar-tip'--这使我们要写的Angular directive。我们改写下html:

[html]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <div id="format-toolbar1" class="settings-button" toolbar-tip="{content: '#format-toolbar-options', position: 'top'}">  
  2.     <img src="http://paulkinzett.github.com/toolbar/img/icon-cog-small.png">  
  3. </div>  

这里需要注意的一点是:我们把toolbar的options全部写到了html中,这样,我们就可以在任意地方使用相同的directive。

最终:

[javascript]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. <script>  
  2. var App = angular.module('Toolbar', []);  
  3.    
  4. App.directive('toolbarTip'function() {  
  5.     return {  
  6.         // Restrict it to be an attribute in this case  
  7.         restrict: 'A',  
  8.         // responsible for registering DOM listeners as well as updating the DOM  
  9.         link: function(scope, element, attrs) {  
  10.             $(element).toolbar(scope.$eval(attrs.toolbarTip));  
  11.         }  
  12.     };  
  13. });  
  14. </script>  

这样就很简单的在Angular中引用了第三方插件。

DEMO

http://jsfiddle.net/codef0rmer/TH87t/

原文地址:

An approach to use jQuery Plugins with AngularJS

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值