从AngularJS中的过滤器调用或编译指令

时间:2015-09-01 11:08:01

标签: javascript angularjs

在AngularJS中,我希望在使用过滤器时调用某些指令。

在这个简化的例子中,我有一个响应<user></user>标签的指令。

我还有一个过滤器,可以将输入转换为这样的标记,即

App.filter('addTags', [
  '$sce', function($sce) {
    return function(input) {
      (input.match(/@[A-Za-z0-9]+/) || []).forEach(function(tag) {
        input = input.replace(tag, '<user name="'+tag+'"></user>')
      });
      return $sce.trustAsHtml(input);
    };
  }
]);

如何正确回复<p ng-bind-html="text | addTags"></p>使user指令编译?

text = 'I call upon a @username'

应编译为'I call upon a <user name="@username"></user>'

由于

1 个答案:

答案 0 :(得分:0)

经过研究,这个问题的正确解决方案是改变&#34; addTags&#34;从过滤器到指令,我们可以在其中重新编译输出以调用其他指令。

App.directive('addtags', ['$compile', function($compile){
  return {
    restrict: 'A',
    scope: {ngModel: '='},
    template: '',
    link: function(scope, elm, attrs) {
      var input = attrs.addtags;
      (input.match(/@[A-Za-z0-9]+/) || []).forEach(function(tag) {
         input = input.replace(tag, '<user name="'+tag+'"></user>')
      });
      elm.append(input);
      $compile(elm.contents())(scope);
    }
  }
}]

作为<p addtags="{{text}}"></p>

调用