【问题标题】:Call custom filter angularjs from controller从控制器调用自定义过滤器 angularjs
【发布时间】:2017-05-10 13:47:01
【问题描述】:

我的场景看起来很简单,但我尝试了很多方法都没有成功。 我需要在我的控制器上调用一个过滤器,这个过滤器是一个面具,把这个 348845697990 变成它 348.8456.979-90。好吧,请按照以下我的代码: 1:我的模块:

angular.module('webclientody', []);

angular.module('webclientody').filter('cpf', function () {
return function (input) {
        var str = input + '';
        if (str.length <= 11) {
            str = str.replace(/\D/g, '');
            str = str.replace(/(\d{3})(\d)/, "$1.$2");
            str = str.replace(/(\d{3})(\d)/, "$1.$2");
            str = str.replace(/(\d{3})(\d{1,2})$/, "$1-$2");
        }
        return str;
    };
});

我的控制器:

angular.module('webclientody').controller('LoginCtrl', function ($scope, 
$http, $location, $cookies, $rootScope, apiUrl, $filter) {

    $scope.init = function () {

        var cpf = "348845697990";
        cpf = $filter("cpf")(cpf);

    };

    $scope.init();

});

如果我剪切这段代码并在一个单独的小项目上对其进行测试,它就可以工作。但是,在我的项目中出现了错误:

> Error: [$injector:unpr] http://errors.angularjs.org/1.5.5/$injector/unpr?p0=cpfFilterProvider%20%3C-%20cpfFilter
    at angular.js:38
    at angular.js:4458
    at Object.d [as get] (angular.js:4611)
    at angular.js:4463
    at Object.d [as get] (angular.js:4611)
    at angular.js:19531
    at b.$scope.init (LoginCtrl.js:6)
    at new <anonymous> (LoginCtrl.js:10)
    at Object.invoke (angular.js:4665)
    at R.instance (angular.js:10115)

我尝试了几种方法,但总是返回此错误。有人有什么建议吗?

非常感谢!

【问题讨论】:

    标签: angularjs filter


    【解决方案1】:

    您错过了注入ngCookies 模块。并检查apiUrl 是否也包括在内。

      angular.module('webclientody', ['ngCookies']);
    

    https://docs.angularjs.org/api/ngCookies/service/$cookies

    【讨论】:

    • 哥们,没有出错。它根本不应用过滤器。我最终在不使用过滤器的情况下解决了。感谢您的回答!
    【解决方案2】:

    尝试将cpf 过滤器注入您的控制器:

    angular.module('webclientody')
           .controller('LoginCtrl', function ($scope, $http, $location, $cookies, $rootScope, apiUrl, cpf) {}
    

    并按如下方式使用:

    var testData = "348845697990";
    cpf(testData);
    

    【讨论】:

    • 过滤器是由 angular.module('webclientody') 它自己创建的。所以我们不需要注入cpf。
    • @ManikandanVelayutham injection $filter 基本上会注入所有过滤器,包括内置过滤器和自定义过滤器。而我提供的方式只会注入目标过滤器。有时我们会需要第二种方式。
    猜你喜欢
    • 2014-10-22
    • 2013-11-29
    • 2014-12-31
    • 1970-01-01
    • 2020-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-10-14
    相关资源
    最近更新 更多