您的位置:首页 > Web前端 > AngularJS

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

2017-05-21 13:38 519 查看

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

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

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息