AngularJS控制器中应用滤镜 [英] AngularJS apply filter in controller

查看:193
本文介绍了AngularJS控制器中应用滤镜的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 AngularJS Web应用程序和过滤器的根控制器。如果我在 HTML 模板应用它过滤器的工作原理,但如果我想要在控制器中应用滤镜这是行不通的。

I have root controller in my AngularJS web application and filter. Filter works if i apply it in the html template, but it doesn't work if i'm trying to apply filter in the controller.

function Controller ( ... deps ...) {
    filter = $filter('my_filter');
    $scope.$apply(function(){$scope.error_message =  filter('ERROR');});
}

过滤必须返回简单的错误字符串到< P> ,这是行不通的。

filter must returns simple error string to the <p>, it doesn't work.

如果我做:

<p>{{'....' | my_filter}}</p>

它的工作原理。为什么呢?

It works. Why?

感谢您。

推荐答案

不要换行 $ scope.error_message =过滤器(错误); 在<$ C 。$ C> $ $范围适用 - 因为控制器是在消化周期调用,这将导致一个错误

Don't wrap $scope.error_message = filter('ERROR'); in $scope.$apply - this will cause an error because the Controller is invoked in a digest cycle.

这应该工作:

function Controller ($filter ... other deps ...) {
  var filter = $filter('my_filter');
  $scope.error_message =  filter('ERROR');
}

这篇关于AngularJS控制器中应用滤镜的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆