我正在开发自定义指令,它将为输入元素创建掩码。整个应用程序以基于组件的样式编码,因此每个组件,指令和过滤器都是这样编写的。我需要在这个指令中注入$ filter服务,因为在它的中间某处我需要使用已经建立的过滤器来格式化字符串。不幸的是,我注入$ filter的方式不起作用,我不断收到错误:
未捕获错误:[$ injector:modulerr]由于以下原因无法实例化模块foo: 错误:[$ injector:modulerr]由于以下原因无法实例化模块应用程序: 错误:[$ injector:modulerr]由于以下原因无法实例化模块app.common: 错误:[$ injector:modulerr]由于以下原因,无法实例化模块inputMaskModule: 错误:[$ injector:modulerr]由于以下原因无法实例化模块$ filter: 错误:[$ injector:nomod]模块'$ filter'不可用!您要么错误拼写了模块名称,要么忘记加载它。如果注册模块,请确保将依赖项指定为第二个参数。 http://errors.angularjs.org/1.5.8/$injector/nomod?p0=%24filter
但情况是,在我尝试注入过滤器之前,加载了这个指令并且里面的示例代码没有问题。
这是指令代码。
inputMask.js,用于注册指令代码:
import angular from 'angular';
import InputMask from './inputMask.directive';
const inputMaskModule = angular.module('inputMaskModule', [])
.directive('inputMask', () => new InputMask());
export default inputMaskModule;
和inputMask.directive.js,其中包含指令代码:
export default class inputMask {
constructor() {
this.restrict = 'A';
this.require = ['ngModel'];
}
link($scope, $element, attrs, ngModel) {
console.log('scope:', $scope, 'element:', $element, 'attrs:', attrs, 'ngModel:', ngModel);
const ngModelController = ngModel[0];
// some more code
$element.bind('focus', focusInput);
$element.bind('blur', blurInput);
}
}
我试过像这样注入$ filter:
const inputMaskModule = angular.module('inputMaskModule', ['$filter'])
.directive('inputMask', ($filter) => new InputMask($filter));
和
constructor($filter) {
this.$filter = $filter;
this.restrict = 'A';
this.require = ['ngModel'];
}
后来我打算用这个。$ filter('someFilter')(someVar)执行$ filter代码来过滤someVar。
但是,上述注射会导致我在问题开始时发布错误。真的不知道如何注入服务,而无需重新设计整个指令 - 这不是我更喜欢的解决方案。
感谢最终的帮助。