当前位置: 移动技术网 > IT编程>脚本编程>AngularJs > 如何在AngularJs中调用第三方插件库

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

2018年04月26日  | 移动技术网IT编程  | 我要评论

在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中引用了第三方插件。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网