[英]Angular: ui-router link not working inside directive
我正在嘗試將ui-router鏈接放在指令“模板”內。
問題:單擊鏈接沒有任何作用。
.directive('hashfinder', function() {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var content = $attrs.content;
var html = content.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, function(match, p1, p2, offset) {
var id = "r" + Math.random();
// Here: ui-sref doesn't work.
return p1 + '<a href="#" ui-sref="app.lounge" class="eva-hash-highlight2">' + p2 + '</a>';
});
$element.html(html);
}
}
})
使用位置:
// inside of ng-repeat
<div ng-if="someBool">
Published a snippet
<span class="eva-event-snipContent" content="{{ event._chirp._comments[0].content }}" hashfinder></span>
</div>
加床@下午4:12
使用@softvar的答案,我收到此錯誤:
jqLite不支持通過選擇器查找元素! 參見: http : //docs.angularjs.org/api/angular.element
原因是sref-url
元素未編譯。 基本上,您需要編譯HTML字符串,然后附加它。
.directive('hashfinder', function($compile) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var content = $attrs.content;
var html = content.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, function(match, p1, p2, offset) {
var id = "r" + Math.random();
// Here: ui-sref doesn't work.
return p1 + '<a href="#" ui-sref="app.lounge" class="eva-hash-highlight2">' + p2 + '</a>';
});
$element.html($compile(angular.element(html))($scope).html());
}
}}
您需要編譯HTML字符串,因為它在角度范圍之外進行了更新。 為此使用$compile
服務。
.directive('hashfinder', function($compile) {
return {
restrict: 'A',
link: function($scope, $element, $attrs) {
var content = $attrs.content;
var html = content.replace(/(^|\W)(#[a-z\d][\w-]*)/ig, function(match, p1, p2, offset) {
var id = "r" + Math.random();
// Here: ui-sref doesn't work.
return p1 + '<a href="#" ui-sref="app.lounge" class="eva-hash-highlight2">' + p2 + '</a>';
});
$element.html($compile(angular.element(html))($scope));
}
}
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.