2017-05-10 118 views
0

我的場景看起來很簡單,但我嘗試了許多沒有成功的方法。 我需要在我的控制器上調用一個過濾器,這個過濾器用於掩碼,把這個348845697990變成348.8456.979-90。好了,按照我的代碼如下: 1:我的模塊:從控制器調用自定義過濾器angularjs

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) 

我試過多種方法,但它總是返回此錯誤。任何人有任何建議?

需要很多!

回答

0

您錯過了注入ngCookies模塊。並檢查apiUrl也包括或不包括。

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

https://docs.angularjs.org/api/ngCookies/service/ $餅乾

+0

韓國社交協會的回答,遺憾的是它不工作。 –

+0

你在控制檯中遇到了什麼錯誤? –

+0

好友,沒有錯誤發生。它根本不適用過濾器。我最終解決了沒有使用過濾器。感謝您的答案! –

0

嘗試注入cpf過濾器控制器:

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

和如下使用它:

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

過濾器是由angular.module('webclientody')創建的。所以我們不需要注入cpf。 –

+0

@ManikandanVelayutham注入'$ filter'基本上會注入所有過濾器,包括內置過濾器和自定義過濾器。我提供的方式只會注入目標過濾器。有時我們需要第二種方式。 – Pengyy

相關問題