簡體   English   中英

角度:ui-router鏈接在指令內部不起作用

[英]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的答案,我收到此錯誤:

jqLit​​e不支持通過選擇器查找元素! 參見: 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM