【问题标题】:My filter does not work我的过滤器不起作用
【发布时间】:2014-10-10 19:46:28
【问题描述】:

我正在尝试将我的状态值从数字更改为“文本”

我想知道如何解决它,我做错了什么?提前谢谢你

      <table>
         <tr ng-repeat="x in Id">
                <td>{{ x.id }}</td>
                <td>{{ x.status | status}}</td>
            </tr>
        </table>

当我写 |状态

    var app = angular.module('customersController', []);

    function customersController($scope, $http) {

     $http.get("localhost")
            .success(function (response) {
                $scope.Id = response;

            });

    app.filter('status', function () {
        return function (input) {
            var statu;
            switch (input) {
                case 10:
                    statu = 'Bronze';
                    break;
                case 20:
                    statu = 'Silver';
                    break;
                case 30:
                    statu = 'Gold';
                    break;
                case 40:
                    statu = 'Elite';
                    break;

            }

            return statu;
        };
    });

【问题讨论】:

  • 不应该是return statu而不是点吗?
  • 对不起,我错过了,但仍然无法正常工作
  • 打开控制台,有什么错误吗?
  • response 中返回的内容是什么?
  • 没有返回响应

标签: angularjs angularjs-filter


【解决方案1】:

您正在控制器内定义过滤器。那是无效的。您只能在配置阶段、启动应用程序和实例化控制器之前向模块添加过滤器。代码应该是:

var app = angular.module('customersController', []);
app.filter('status', function () {
    return function (input) {
        var statu;
        switch (input) {
            case 10:
                statu = 'Bronze';
                break;
            case 20:
                statu = 'Silver';
                break;
            case 30:
                statu = 'Gold';
                break;
            case 40:
                statu = 'Elite';
                break;
        }
        return statu;
    };
});

app.controller('customersController', function($scope, $http) {
     $http.get("localhost")
        .success(function (response) {
            $scope.Id = response;
        });
});

【讨论】:

  • 我上传了plunker
  • 不,你没有。 JS 文件中可能没有&lt;script&gt; 标签。 &lt;script&gt; 标签进入 HTML 文件。而且您的 HTML 文件没有任何 ng-app,也没有使用您的控制器。另外,你希望$http.get("localhost")做什么?
  • 我得到
  • 是的,我错过了在正文中为我的 ngapp 命名,然后将其放入 angularmodule。它现在工作,谢谢你的帮助
猜你喜欢
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-16
  • 2014-08-24
  • 2018-01-04
  • 2020-12-23
相关资源
最近更新 更多