下面的工作和控制台点记录“post”对象,但是如何将指令中锚点标记的url传递给控制器函数“itemClicked” ?Angular指令将参数传递给控制器函数在元素的.html()
HTML:
<div ng-repeat="post in posts" >
<div find-urls link-clicked="itemClicked(post)" ng-bind="post.content"><div>
</div>
控制器:
$scope.itemClicked = function(post) {
console.log(post);
};
指令:
function findUrls($compile) {
return {
restrict: 'AC',
scope: {
linkClickedCallback: '&linkClicked'
},
link: function (scope, elem, attrs) {
if (attrs.ngBind) {
scope.$watch(attrs.ngBind, _.debounce(wrapUrls));
}
if (attrs.ngBindHtml) {
scope.$watch(attrs.ngBindHtml, _.debounce(wrapUrls));
}
function wrapUrls(text) {
var linkPatterns = new Array({
pattern: /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
template: ' <a class="absolute_link" href="$1" target="_blank">$1</a>'
},
{
pattern: /(^|[^\/])(www\.[\S]+(\b|$))/ig,
template: ' <a class="absolute_link" href="http://$2" ng-click="linkClickedCallback();" target="_blank">$2</a>'
},
{
pattern: /([a-z0-9._-][email protected][a-z0-9._-]+\.[a-zA-Z0-9._-]+)/ig,
template: ' <a class="absolute_link" href="mailto:$1" ng-click="linkClickedCallback();" target="_blank">$1</a>'
},
{
pattern: /(^|[^[email protected]\\\/._-])([a-z0-9]{0,256}\.(com|net|org|edu)([a-z0-9\/?=\-_#]{0,256})?(\b|$))/ig,
template: ' <a class="absolute_link" href="http://$2" ng-click="linkClickedCallback();" target="_blank">$2</a>'
});
var html = elem.html();
var newHtml = html;
linkPatterns.forEach((item) => {
newHtml = newHtml.replace(item.pattern, item.template);
});
if (html !== newHtml) {
elem.html(newHtml);
$compile(elem.contents())(scope);
}
}
}
};
}
[从指令到控制器传递AngularJS范围变量的最简单方法是什么?](https://stackoverflow.com/questions/13318726/easiest-way-to-pass-an-angularjs-scope-variable-从指令到控制器) – Maher
我认为它略有不同。在我的情况下,我需要对HTML元素进行ng单击来触发控制器函数调用并传入参数。这是我无法工作的原因。 – Chris
,这意味着你尝试从Html发送参数,如下所示:'link-clicked =“itemClicked('etc')”' – Maher