【问题标题】:AngularJS - $interpolate vs $filterAngularJS - $interpolate vs $filter
【发布时间】:2025-12-03 23:00:02
【问题描述】:

在 AngularJS 中,$filter 提供了一种格式化我们向用户显示的数据的方法。 但是,$interpolate 也允许我们实时更新字符串 的文本。

$interpolate$filter 是否相互关联?这两者在概念上有何不同?

【问题讨论】:

    标签: javascript angularjs angularjs-filter angularjs-interpolate


    【解决方案1】:

    您可以将 $interpolate() 视为一个专门的过滤器。

    var interpolationFunction = $interpolate('{{thing}} is {{color}}.');
    
    var grass = {thing: 'Grass', color: 'green'};
    console.log(interpolationFunction(grass));
    
    // Or just.
    console.log(interpolationFunction({thing: 'Milk', color: 'white'}));
    console.log(interpolationFunction({thing: 'The sky', color: 'blue'}));
    

    这将产生:

    Grass is green.
    Milk is white.
    The sky is blue.
    

    您可以将 $interpolate(STRING) 的返回值视为您稍后使用一组变量呈现的已编译模板。

    相比之下,$filter(NAME) 返回一个以前注册为名称为 NAME 的过滤器的函数。例如,“大写”过滤器将其参数转换为大写,“数字”过滤器格式化数字,“日期”过滤器格式化 Date 对象,您可以定义自己的命名过滤器,使用其参数执行任意操作。

    【讨论】: