【问题标题】:Angular Js filter does not work with javascript addition operatorAngular Js 过滤器不适用于 javascript 加法运算符
【发布时间】:2016-09-24 17:37:57
【问题描述】:

当我遇到以下问题时,我正在使用 Angular Js

<li ng-repeat="x in capitals | orderBy:'capital'">
{{ x.country|uppercase}} : {{ x.capital|uppercase}}
</li>

有效但

<li ng-repeat="x in capitals | orderBy:'capital'">
{{ x.country|uppercase+ ":" + x.capital|uppercase}} 
</li>

没用

有什么解决办法吗?

【问题讨论】:

    标签: javascript angularjs operator-keyword angularjs-filter addition


    【解决方案1】:

    这不起作用,因为您不能在表达式中使用加法运算符。您可以编写自定义过滤器并使用它。检查下面的小提琴。

      jsfiddle.net/7nzot7jh/
    

    【讨论】:

    • 试过
      • {{ showMovie(x.country) + ":" + x.capital }}
    【解决方案2】:

    找到答案 这是我的自定义过滤器

            app.filter('alterCap',function() 
            {
                return function(x) 
                {
                    var i, c, txt = "";
                    for (i = 0; i < x.length; i++) {
                        c = x[i];
                        if (i % 2 == 0) {
                            c = c.toUpperCase();
                        }
                        txt += c;
                    }
                    return txt;
                };
            });
    

    在我的控制器中我已经通过了

    app.controller("myCtrl",function($scope,$filter){
                    $scope.capitals = [
                    {country:'India',capital:'Delhi'},
                    {country:'Sri Lanka',capital:'Colombo'},
                    {country:'Afganistan',capital:'Kabul'},
                    {country:'Bhutan',capital:'Norway'},
                    {country:'Nepal',capital:'Thimphu'},
                    {country:'Japan',capital:'Tokyo'},
                    {country:'China',capital:'Beijing'},
                    {country:'Russia',capital:'Moscow'},
                    {country:'USA',capital:'Washington, D.C.'}
                    ];
                    $scope.applyAlterCap = function(movie){
                        return $filter('alterCap')(movie);
                    };
                });
    

    现在我可以在我的表达式中使用过滤器了

            <p>Using Custom Filter with addition operator inside expression</p>
            <ul>
                <li ng-repeat="x in capitals | orderBy:'capital'">
                    {{ applyAlterCap(x.country) + ":" + x.capital }}
                </li>
            </ul>
    

    【讨论】:

      【解决方案3】:
      {{ x.country + ":" + x.capital}}
      

      【讨论】:

        猜你喜欢
        • 2016-12-02
        • 2018-11-22
        • 1970-01-01
        • 2014-05-05
        • 1970-01-01
        • 2021-12-09
        • 1970-01-01
        • 2015-01-12
        • 2021-01-20
        相关资源
        最近更新 更多