2017-09-08 112 views
1

在我的网站上显示的文字,我想规范链接到其他人看起来像这样,所以我做了它一个指令:包含指令

<my-person id="1"></my-person> 

app.directive('myPerson', function() { 
    return { 
    restrict: 'E', 
    replace: 'true', 
    template: '<a href="#/person/{{person.id}}">{{person.name}}</a>', 
    scope: { 
     person_id : '=id', 
    }, 
    controller: function($scope, Repository) { 
     Repository.getPerson($scope.person_id).then(function(p) { 
      $scope.person = p; 
     }); 
    }, 
    }; 
}); 

该作品好。

但是在下一步,我希望用户写新闻,并在他们想要引用其他人的新闻。所以基本上,我想显示一个文本

'I met <my-person id="42"></my-person> yesterday.' 

但当angularjs显示我的新闻条目的背景下,然后将HTML标签转义,当然,它也不会被编译。

有没有简单的方法来实现这一目标?这里是一个jsfiddle,显示我的问题:jsfiddle link

回答

2

您将需要在ng-repeat块内编译你的html。

为了使像下面

app.directive('bindHtmlCompile', ['$compile', function ($compile) { 
     return { 
      restrict: 'A', 
      link: function (scope, element, attrs) { 
       scope.$watch(function() { 
        return scope.$eval(attrs.bindHtmlCompile); 
       }, function (value) { 
        element.html(value); 
        $compile(element.contents())(scope); 
       }); 
      } 
     }; 
    }]); 

现在里面你的NG-重复你的指令添加到跨度这样的指令:

<span class="row" bind-html-compile="newsEntry.text"></span> 

工作代码here

参考here