AngularJS

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > AngularJS > angularjs 第三方插件

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

作者:vuturn

在AngularJs中我们会不可避免的使用第三方库,这篇文章主要介绍了如何在AngularJs中调用第三方插件库,有兴趣的可以了解下

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

如何使用?

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

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

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

<!-- Click this to see a toolbar --> 
<div id="format-toolbar" class="settings-button"> 
  <img src="http://paulkinzett.github.com/toolbar/img/icon-cog-small.png"> 
</div> 
  
<!-- Our tooltip style toolbar --> 
<div id="format-toolbar-options"> 
  <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="icon-align-left"></i></a> 
  <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="icon-align-center"></i></a> 
  <a href="#" rel="external nofollow" rel="external nofollow" rel="external nofollow" ><i class="icon-align-right"></i></a> 
</div> 
<!-- Typical jQuery plugin invocation --> 
$('#format-toolbar').toolbar({ 
  content: '#format-toolbar-options',  
  position: 'left' 
}); 

在Angular中使用

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

<div id="format-toolbar1" class="settings-button" toolbar-tip="{content: '#format-toolbar-options', position: 'top'}"> 
  <img src="http://paulkinzett.github.com/toolbar/img/icon-cog-small.png"> 
</div> 

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

<script> 
var App = angular.module('Toolbar', []); 
  
App.directive('toolbarTip', function() { 
  return { 
    // Restrict it to be an attribute in this case 
    restrict: 'A', 
    // responsible for registering DOM listeners as well as updating the DOM 
    link: function(scope, element, attrs) { 
      $(element).toolbar(scope.$eval(attrs.toolbarTip)); 
    } 
  }; 
}); 
</script> 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文