gpt4 book ai didi

javascript - 使用 $filter 时,cloneConnectFn 不是函数

转载 作者:行者123 更新时间:2023-12-03 06:47:10 29 4
gpt4 key购买 nike

我正在开发一个使用 Typescript 和 Angular 生成动态 Web 内容的项目。目前,我的工作是将输入字段格式化为货币,这在普通的javascript(带有 Angular )中非常简单,但我需要在 typescript 中完成,这会带来一些问题。这是我的指令(我根据建议的另一个堆栈溢出答案将其格式化为类)

namespace incode.directives.label {
interface IScope extends ng.IScope {
amount: number;
}
export class IncodeCurrencyInputDirective implements ng.IDirective {
restrict ='A';
public require: 'ngModel';
public scope: Object;
replace = true;
public link: ng.IDirectiveLinkFn | ng.IDirectivePrePost;


constructor(private $filter: ng.IFilterService) {
this.scope = {
amount: '='
};
this.link = (scope: IScope, element: ng.IAugmentedJQuery, attrs: ng.IAttributes, ctlr: any, $filter: ng.IFilterService) => {
//element.bind('focus',
// function () {
// element.val(scope.amount);
// });
element.bind('input',
function () {
scope.amount = element.val();
scope.$apply;
});
element.bind('blur',
function () {
element.val($filter('currency')(scope.amount));
});

}
}




public static factory(): ng.IDirectiveFactory {
var directive = ($filter) => new IncodeCurrencyInputDirective($filter);
directive.$inject = ['$filter'];
return directive;
}


}

angular.module('incode.module')
.directive('ixCurrency', incode.directives.label.IncodeCurrencyInputDirective.factory());
}

这是使用它的模板

<md-input-container layout-fill class="number-range">
<input placeholder="From"
type="text"
name="from"
ix-currency
amount="0.00"
precision="{{rangeController.precision}}"
ng-model="rangeController.Bucket.RangeFilterFromString"/>
</md-input-container>

就目前而言,脚本会在模糊时生成错误: TypeError:cloneConnectFn is not a function 这似乎是 Angular 使用的非常低级的函数,通常不应使用会产生这个错误。非常感谢您提供的任何见解!

编辑:因为我知道很多 Angular 专家从未接触过 typescript ,所以我将附上编译后的 JavaScript 的粘贴箱,以防有帮助 http://pastebin.com/NnTLqauL

最佳答案

我明白了,不知道为什么它会给我这个错误,但问题的根源是 typescript 和 Angular 之间的范围沟通不畅。你会注意到我有这条线

element.val($filter('currency')(scope.amount));

在上面的'blur'绑定(bind)中。我以这种方式引用过滤器的原因是,如果您编写 this.$filter, typescript 会对其进行编译,即使它位于对象内部,this 也会引用 window 而不是对象,因此 $filter 超出了范围。解决方案是使用 lambda 函数来欺骗范围,如下所示:

element.bind('blur',
() => {
element.val(this.$filter('currency')(scope.amount));
});

始终注意 this 指向的位置(这对我来说似乎非常困难),你应该没问题。

关于javascript - 使用 $filter 时,cloneConnectFn 不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37684107/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com