在AngularJs中我们会不可避免的使用第三方库,例如jquery插件库。我们不能散乱的在AngularJS中引入这些库,例如在controller中。那么应该怎么在Angular中使用第三方库呢?
如何使用?
很简单,给插件写一个directive。
在这里,我会使用一个简单的jquery插件Toolbar.js 的DEMO。
这是我们如何在jquery中创建一个tooltip的:
-
- <div id="format-toolbar" class="settings-button">
- <img src="http://paulkinzett.github.com/toolbar/img/icon-cog-small.png">
- </div>
-
-
- <div id="format-toolbar-options">
- <a href="#"><i class="icon-align-left"></i></a>
- <a href="#"><i class="icon-align-center"></i></a>
- <a href="#"><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: 'A',
-
- link: function(scope, element, attrs) {
- $(element).toolbar(scope.$eval(attrs.toolbarTip));
- }
- };
- });
- </script>
这样就很简单的在Angular中引用了第三方插件。
DEMO
原文地址: