在过滤器angularjs中使用范围



我正试图创建一个过滤器来监视safe,并尝试在变量上使用$compile

现在我可以使用这个没有问题的

.directive('safe', ['$compile',
    function ($compile) {
      return function (scope, element, attrs) {console.log(scope, element, attrs)
        scope.$watch(
          function (scope) {
            // watch the 'safe' expression for changes
            return scope.$eval(attrs.bindUnsafeHtml);
          },
          function (value) {
            // when the 'safe' expression changes
            // assign it into the current DOM
            element.html(value);
            // compile the new DOM and link it to the current
            // scope.
            // NOTE: we only compile .childNodes so that
            // we don't get into infinite loop compiling ourselves
            $compile(element.contents())(scope);
          }
        );
      };
    }
  ])

html文件中上述代码的用法是

<span safe="'_agree_to_terms_and_conditions_'">

现在我想能够做这样的事情,而不是

 {{ gettext("_agree_to_terms_and_conditions_" | safe }}

现在,当我尝试创建filter时,那里没有可用的scope。。。

甚至有可能达到上面的效果吗?

PS。过滤器的名称需要与给定的示例完全匹配,因为我正试图在i18n的不同应用程序中创建该函数的通用用法。

这似乎是个坏主意。对于filter,您不希望尝试以任何方式修改$scope。您可能会在$digest周期中出现错误。但是有可能将事物传递到filter中。

{{ gettext("_agree_to_terms_and_conditions_" | safe:this }}
app.filter('safe', function () {
   return function (input, scope) {
     //scope will be *this* that you passed in from the HTML
   };
});

刚刚发现一篇文章,之前有人问过这个问题:从AngularJS中的过滤器访问范围变量。他们也给出了类似的警告,不要试图修改$scope

最新更新