创建一个过滤器以在Angular JS中编译动态字符串

时间:2014-01-27 20:07:14

标签: javascript angularjs

我是刚刚接触到角度JS并刚刚掌握它,我试图创建一个过滤器,它将编译存储在数据库中的给定字符串。下面的HTML将history.activity传递给我的动态过滤器,其中:this附加传递给当前范围。

<ul>
  <li ng-repeat="history in recentActivity">
    {{ history.activity | dynamic:this }}</p>
  </li>
</ul>

history.activity变量包含一个Angular模板格式的字符串,如下所示,这些字符串会根据记录的活动从数据库中提取而变化。

{{ history.username }} logged in at {{ history.created_date | date }}

我的下面的过滤器是非常基本的,应该编译源,但它只是返回undefined .....

app.filter('dynamic', function ($compile) {
  return function (source, scope) {
    return $compile(source)(scope);
  };
});

有什么想法吗?我在哪里错了?非常感谢任何帮助:)

2 个答案:

答案 0 :(得分:3)

如果您的activity变量不包含HTML而只包含角度表达式,那么您需要使用$interpolate代替$compile - check the angular.js docs for it

如果您需要动态添加一些HTML,那么您需要Jonathan所说的指令 - 过滤器不能用于包含HTML。

但实际上我还是建议使用指令 - 编译/插值都比较慢,所以最好只在你的表达式改变时调用它们(这可以通过$watch调用指令来实现)。每个摘要周期都会调用两次过滤表达式,如果您经常使用此过滤器,则可能会遇到性能问题。

答案 1 :(得分:1)

使用DOM时,您需要一个指令。

<li ng-repeat="history in recentActivity" fun-times="history"></li>

指令:

app.directive("funTimes", function($compile){
   return{
     restrict: 'A',
     scope:{funTimes:'='},
     link: function(scope, element, attributes){
       scope.watch('funTimes', function(){              
         $compile(scope.funTimes)(scope, function(cloned, scope){ 
           element.html(cloned); 
         });
       });
     }
   }
}

我没有对此进行测试,这只是我的头脑。