[英]add a “bookmark page” button with angular
I've seen a couple of js snippets to bookmark a page, like this one: http://www.thewebflash.com/2014/12/how-to-add-cross-browser-add-to.html 我已经看到了几个js片段来将页面添加为书签,就像这样: http : //www.thewebflash.com/2014/12/how-to-add-cross-browser-add-to.html
Basically they call different js method depending on the browser, dynamically create an href with rel=sidebar in ff, or prompt the user to manually add it if it's not supported on that browser. 基本上,他们会根据浏览器调用不同的js方法,在ff中使用rel = sidebar动态创建href,或者提示用户手动添加该浏览器(如果该浏览器不支持)。
I was wondering what would be the cleanest way to achieve this in an angular app? 我想知道在有角度的应用程序中最干净的方法是什么? I searched for a directive that could accomplish it but couldn't find any.
我搜索了可以完成该指令但找不到任何指令的指令。
Here is a simple directive implementing that feature: 这是实现该功能的简单指令:
angular.module("myApp", [])
.directive("bookmarkPage", function ($window, $location) {
return {
restrict: "AEC",
link: function (scope, element, attrs) {
$(element).click(function (e) {
var bookmarkURL = window.location.href;
var bookmarkTitle = document.title;
var triggerDefault = false;
if (window.sidebar && window.sidebar.addPanel) {
// Firefox version < 23
window.sidebar.addPanel(bookmarkTitle, bookmarkURL, '');
} else if ((window.sidebar && (navigator.userAgent.toLowerCase().indexOf('firefox') > -1)) || (window.opera && window.print)) {
// Firefox version >= 23 and Opera Hotlist
var $this = $(this);
$this.attr('href', bookmarkURL);
$this.attr('title', bookmarkTitle);
$this.attr('rel', 'sidebar');
$this.off(e);
triggerDefault = true;
} else if (window.external && ('AddFavorite' in window.external)) {
// IE Favorite
window.external.AddFavorite(bookmarkURL, bookmarkTitle);
} else {
// WebKit - Safari/Chrome
alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != -1 ? 'Cmd' : 'Ctrl') + '+D to bookmark this page.');
}
return triggerDefault;
});
}
}
});
Still you can replace those window
and window.loaction
with $window
and $location
to make it easily testable. 仍然可以用
$window
和$location
替换那些window
和window.loaction
以使其易于测试。
In your HTML: 在您的HTML中:
<a id="bookmark-this" href="#" title="Bookmark This Page" bookmark-page>Bookmark This Page</a>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.