我正在开发一个Ionic应用程序,用户可以在其中发布降价内容。为了使这项工作,我正在使用带角度标记的库。在应用程序中,我希望在操作系统的默认浏览器中打开所有markdown链接,因此我做了两件事。
我编写了一个角度指令,使用ngCordova包装器为cordova-plugin-inappbrowser强制链接在OS的浏览器中打开。
我已经设置了angular-marked的配置,以使用此伪指令渲染所有链接。
问题是链接无法在系统浏览器中打开。它们在当前的WebView中打开。可能是我的指令是错误的,或者在这种情况下指令甚至都不是正确的选择。
我在代码中干什么?我该如何解决在系统浏览器中打开链接的问题?
.directive('fab-extLink', ['$cordovaInAppBrowser', function($cordovaInAppBrowser){
return {
restrict: 'A',
link: function(scope, elem, attrs) {
elem.bind('click', function(e) {
// Stop the link from opening.
e.preventDefault();
// Open the link with the operating system browser.
$cordovaInAppBrowser.open(attrs.href, '_system');
});
}
};
}])
.config( [
'$compileProvider',
'markedProvider',
function( $compileProvider, markedProvider)
{
$compileProvider.aHrefSanitizationWhitelist(/^\s*(https?|ftp|mailto|chrome-extension):/);
// When markdown is rendered use the external link directive.
markedProvider.setRenderer({
link: function(href, title, text) {
return '<a fab-extLink href="' + href + '"' + (title ? ' title="' + title + '"' : '') + '>' + text + '</a>';
}
});
}
])
您的代码有两个问题
camelCase
,它将转换为kebab-case
HTML。这很容易修复,只需更改即可 .directive('fab-extLink', ['$cordovaInAppBrowser', function($cordovaInAppBrowser){
到
.directive('fabExtlink', ['$cordovaInAppBrowser', function($cordovaInAppBrowser){
<a fab-extlink>
HTML中有,但是angular没有$compile
(实例化)它。这是一个困难的过程(如果您不想用猴子标记角度标记)。
angular-marked
用于element.html(marked(text, scope.opts || null));
设置元素的内部HTML,它会跳过angular的编译过程,因此不会初始化指令。
一种解决方法是使用全局函数(我知道不是很优雅):
在app.run中定义它:
.run(function ($cordovaInAppBrowser) {
window.openInSystemBrowser=function(link){
$cordovaInAppBrowser.open(link, '_system');
};
并配置有角度标记以使用onclick,因此它独立于angular起作用。
markedProvider.setRenderer({
link: function (href, title, text) {
return '<a onclick="openInSystemBrowser(\'' + href + '\')"' + (title ? ' title="' + title + '"' : '') + '>' + text + '</a>';
}
});
我可以想到的另一种方法是分叉和修补有角度的标记。
angular-marked.js
代替
element.html(marked(text, scope.opts || null));
和
element.replaceWith($compile(marked(text, scope.opts || null))(scope));
我检查了该存储库,最新版本的带角度标记(v1.2)支持名为的属性compile
,即可完成此操作。
例如
<marked compile="true">
# Markdown [Google](http://www.google.com)
*It works!*
</marked>
因此,总而言之。
.directive('fab-extLink', ...
到
.directive('fabExtlink', ...
compile='true'
到<marked>
指令本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句