在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中引用了第三方插件。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答